用函数计算1+2+4+6+...+100的的和
时间: 2023-12-25 10:05:24 浏览: 27
以下是用函数计算1+2+4+6+...+100的和的方法:
```c
#include <stdio.h>
int sum(int n) {
if (n == 0) {
return 0;
} else {
return 2 * n + sum(n - 1);
}
}
int main() {
int n = 50;
printf("1+2+4+6+...+100的和为:%d", sum(n));
return 0;
}
```
相关问题
设计递归函数计算1+2+3+...+100和5!。
以下是设计递归函数计算1+2+3+...+100和5!的代码:
```c++
#include <iostream>
using namespace std;
// 计算1+2+3+...+n的递归函数
int sum(int n) {
if (n == 1) {
return 1;
}
return n + sum(n - 1);
}
// 计算n的阶乘的递归函数
int factorial(int n) {
if (n == 1) {
return 1;
}
return n * factorial(n - 1);
}
int main() {
// 计算1+2+3+...+100
int s = sum(100);
cout << "1+2+3+...+100 = " << s << endl;
// 计算5!
int f = factorial(5);
cout << "5! = " << f << endl;
return 0;
}
```
在Python中用函数计算1+2+4+6+...+100的的和
以下是Python中用函数计算1+2+4+6+...+100的和的方法:
```python
def sum_of_series(n):
sum = 0
for i in range(1, n+1):
sum += 2*i if i%2==0 else i
return sum
print(sum_of_series(50)) # 输出:2550
```
该函数使用for循环遍历1到n,如果i是偶数,则将2*i加到总和中,否则将i加到总和中。最后返回总和。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)