计算1+2+......+50的结果值,分别用while do,while for
时间: 2023-12-31 14:05:13 浏览: 35
1. while循环
```python
i = 1
result = 0
while i <= 50:
result += i
i += 1
print(result)
```
2. do-while循环(Python中没有do-while循环)
```python
i = 1
result = 0
while True:
result += i
i += 1
if i > 50:
break
print(result)
```
3. for循环
```python
result = 0
for i in range(1, 51):
result += i
print(result)
```
相关问题
分别使用for,while,do-while语句计算sum=1+2+...+n的值
使用for循环语句计算sum=1+2+...+n的值的代码如下:
```
int sum = 0;
for(int i = 1; i <= n; i++){
sum += i;
}
```
使用while循环语句计算sum=1+2+...+n的值的代码如下:
```
int sum = 0;
int i = 1;
while(i <= n){
sum += i;
i++;
}
```
使用do-while循环语句计算sum=1+2+...+n的值的代码如下:
```
int sum = 0;
int i = 1;
do{
sum += i;
i++;
}while(i <= n);
```
用分别用for,while,dowhile计算1!+2!+3!+...+n!
好的,这是一个数学问题,可以使用循环语句进行计算。
使用for循环计算:
```
int n = 5;
int result = 1;
for (int i = 1; i <= n; i++)
{
result *= i; // 相当于result = result * i;
}
```
使用while循环计算:
```
int n = 5;
int result = 1;
int i = 1;
while (i <= n)
{
result *= i; // 相当于result = result * i;
i++;
}
```
使用do-while循环计算:
```
int n = 5;
int result = 1;
int i = 1;
do
{
result *= i; // 相当于result = result * i;
i++;
} while (i <= n);
```
以上三种循环语句都可以得到1! 2! 3! ... n!的阶乘结果,其中n=5时,结果为120。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![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)