2.分别用while和for循环编程,实现求一下数列前20项之和 2/1, 3/2, 5/3, 8/5, 13/8, ……
时间: 2023-12-13 14:32:47 浏览: 63
以下是使用while和for循环分别实现求数列前20项之和的C语言代码:
1.使用while循环:
```c
#include <stdio.h>
int main() {
double sum = 0, a = 2, b = 1, c, term;
int i = 1;
while (i <= 20) {
term = a / b;
sum = sum + term;
c = a + b;
b = a;
a = c;
i++;
}
printf("The sum is: %.2f\n", sum);
return 0;
}
```
2.使用for循环:
```c
#include <stdio.h>
int main() {
double sum = 0, a = 2, b = 1, c, term;
int i;
for (i = 1; i <= 20; i++) {
term = a / b;
sum = sum + term;
c = a + b;
b = a;
a = c;
}
printf("The sum is: %.2f\n", sum);
return 0;
}
```
相关问题
1、分别用while循环、do~while循环或for循环编程有一分数序列:求这个数列的前20项之和。
我们可以使用for循环来求这个数列的前20项之和,代码如下:
```c++
#include <iostream>
int main() {
int sum = 0;
for (int i = 1; i <= 20; i++) {
sum += i;
}
std::cout << "前20项之和为:" << sum << std::endl;
return 0;
}
```
输出结果为:
```
前20项之和为:210
```
使用while循环或do-while循环也可以实现同样的功能,代码如下:
```c++
#include <iostream>
int main() {
int sum = 0;
int i = 1;
while (i <= 20) {
sum += i;
i++;
}
std::cout << "前20项之和为:" << sum << std::endl;
return 0;
}
```
```c++
#include <iostream>
int main() {
int sum = 0;
int i = 1;
do {
sum += i;
i++;
} while (i <= 20);
std::cout << "前20项之和为:" << sum << std::endl;
return 0;
}
```
它们的输出结果也都为:
```
前20项之和为:210
```
1、分别用while循环、do~while循环或for循环编程有一分数序列:求这个数列的前20项之和。
使用for循环编程实现:
```python
sum = 0
for i in range(1, 21):
sum += i
print("前20项之和为:", sum)
```
使用while循环实现:
```python
sum = 0
count = 1
while count <= 20:
sum += count
count += 1
print("前20项之和为:", sum)
```
使用do-while循环实现:
Python中没有do-while循环,可以通过while循环加上一个判断条件来实现:
```python
sum = 0
count = 1
while True:
sum += count
count += 1
if count > 20:
break
print("前20项之和为:", sum)
```
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.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)