c语言用递归求和1+2+3+4+...+n
时间: 2023-05-28 18:05:29 浏览: 98
#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
}
}
相关问题
C语言实现1+2+3+...+100
在C语言中,可以使用循环语句来实现求和。以下是一个简单的示例代码,用于计算从1到100的所有整数之和:
```c
#include <stdio.h>
int main() {
int sum = 0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
printf("1 + 2 + 3 + ... + 100 = %d\n", sum);
return 0;
}
```
在上述代码中,我们首先定义了一个变量`sum`,用于存储求和结果。然后使用`for`循环语句,从1到100遍历所有整数,并将它们累加到`sum`变量中。最后使用`printf`函数输出结果。
需要注意的是,在实际应用中,可能需要根据具体需求对代码进行适当的修改和优化。例如,如果需要求和的数字范围较大,可以考虑使用高精度算法或利用计算机的浮点数运算能力来提高计算效率。此外,还可以使用递归算法或动态规划算法等更高级的方法来求解大规模问题。
如何用c语言编程求1+2+3+4+....+n
以下是两种C语言编程求1+2+3+4+....+n的例子:
1. 使用for循环求和
```c
#include <stdio.h>
int main(void) {
int n = 0;
int i = 0;
int sum = 0;
printf("请输入n的值:");
scanf("%d", &n);
for (i = 1; i <= n; ++i) {
sum = sum + i;
}
printf("sum = %d\n", sum);
return 0;
}
```
2. 使用递归函数求和
```c
#include <stdio.h>
#include <stdlib.h>
int fun(int m);
int main() {
int n, sum = 0;
printf("Please enter a number:");
scanf("%d", &n);
if (n <= 0) {
printf("Enter error");
exit(0);
}
sum = fun(n);
printf("sum = %d\n", sum);
return 0;
}
int fun(int m) {
if (m == 1) {
return 1;
}
return m + fun(m - 1);
}
```
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)