编程求1+2+3+4
时间: 2023-12-25 11:28:22 浏览: 27
以下是两种Python编程求1+2+3+4的例子:
1.使用for循环
```python
sum = 0
for i in range(1, 5):
sum += i
print(sum) # 输出:10
```
2.使用while循环
```python
sum = 0
i = 1
while i <= 4:
sum += i
i += 1
print(sum) # 输出:10
```
相关问题
如何用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);
}
```
编程求1+1/2+1/3...
以下是C++语言的代码实现,用于计算1+1/2+1/3+...+1/n的和:
```c++
#include<bits/stdc++.h>
using namespace std;
int a,b;
float c;
int main() {
scanf("%d",&a);
for(int i=1;i<=a;i++)
c+=1.0/i*1.0;
printf("%.3f",c);
return 0;
}
```
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)