c语言编写程序,用递归的方法求1+2+3+…+n,可设递归函数为fun5()。 (1)递归结束条件为n=0。 (2)递推公式为n+fun5(n-1)。
时间: 2024-05-25 15:18:00 浏览: 19
#include <stdio.h>
int fun5(int n) {
if (n == 0) { // 递归结束条件
return 0;
} else {
return n + fun5(n-1); // 递推公式
}
}
int main() {
int n;
printf("请输入n:");
scanf("%d", &n);
printf("1+2+...+%d=%d\n", n, fun5(n));
return 0;
}
相关问题
C语言用递归实现1+2+3+...+n的和
以下是C语言用递归实现1+2+3+...+n的和的代码和解释:
```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); // 递归调用
}
```
解释:
1.首先在主函数中输入一个正整数n,如果n小于等于0,则输出“Enter error”并退出程序。
2.然后调用递归函数fun(n),将返回值赋给变量sum。
3.在递归函数fun(m)中,如果m等于1,则返回1,递归结束。
4.否则,返回m+fun(m-1),即m加上m-1到1的和,继续递归调用fun(m-1)。
5.最终,fun(n)返回的值就是1+2+3+...+n的和,赋给sum并输出。
如何用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);
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pptx](https://img-home.csdnimg.cn/images/20210720083543.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)