C语言I/O请用递归实现计算 :1 + 1/3 - 1/5 + 1/7 - 1/9 + .... 1/n 的值,n通过键盘输入
1.代码展示:
2.源码:
#include <stdio.h>
double recursive_sum(int n, int sign) {
if (n == 1) {
return 1.0;
} else {
return sign * (1.0 / n) + recursive_sum(n - 2, -sign);
}
}
int main(int argc, const char *argv[])
{
int n;
printf("请输入n的值: ");
scanf("%d", &n);
if (n % 2 == 0) {
printf("请输入奇数\n");
return 1;
}
double result = recursive_sum(n, 1);
printf("结果: %f\n", result);
return 0;
}