下次在提问的时候还是要说清楚什么开发言语,什么开发环境吧
#include "stdio.h"
int calc(int n)
{
if(n==0)
return 0;
return (n + calc(n-1));
}
void main()
{
printf("%d\n", calc(10));
}
gcc version 4.2.1 20070719 [FreeBSD]下测试通过
我用VB.net的代码给你写一个
private function Count(Byval num as Integer) as Integer
dim i as Integer
dim count as Integer=0
for i = 1 to num
count = i + count
next
return count
end function
调用的时候可以写成
dim n as Integer=100
Count(n)
这样就可以了!
end function
函数的公式是(1+n)*n/2
public class Sum_n {
public static void main(String[] args) {
int n = 100;
int sum = getsum(n);
System.out.println("1+2+3+4+……+ "+n+"sum : "+sum);
}
public static int getsum(int n){
int sum=0;
for(int i=0;i<=n;i++){
sum+=i;
}
return sum;
}
}