c语言用递归求和1+2+3+4+...+n
时间: 2023-05-28 15:05:29 浏览: 137
计算 S=1!+2!+3!+...+N! C语言代码
#include <stdio.h>
int sum(int n);
int main() {
int n;
printf("Enter a positive integer: ");
scanf("%d", &n);
printf("Sum of 1 to %d is %d\n", n, sum(n));
return 0;
}
int sum(int n) {
if (n == 1) { // base case
return 1;
} else {
return n + sum(n-1); // recursive case
}
}
阅读全文