2.分别用while和for循环编程,实现求一下数列前20项之和 2/1, 3/2, 5/3, 8/5, 13/8, ……
时间: 2023-12-13 19:32:47 浏览: 134
以下是使用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;
}
```
相关问题
分别用 while、do-while、for 语句编程,求数列前 20 项之和: 2/1,3/2,5/3, 8/5,13/8 .
这是一个斐波那契数列求和的问题,我们可以分别使用 while、do-while 和 for 循环来实现。这里给出的是 Python 语言的例子:
```python
# While循环
sum = 0
a, b = 1, 1
i = 1
while i <= 20:
sum += a
c = a + b
a, b = b, c
i += 1
print("While循环结果:", sum)
# Do-while循环(Python不直接支持do-while,但可以模拟)
i = 1
while True:
if i > 20:
break
sum += a
c = a + b
a, b = b, c
i += 1
print("Do-while模拟结果:", sum)
# For循环
sum = 0
a, b = 1, 1
for _ in range(20):
sum += a
c = a + b
a, b = b, c
print("For循环结果:", sum)
```
1、分别用while循环、do~while循环或for循环编程有一分数序列:求这个数列的前20项之和。2、输入一串字符,逆序输出。要求使用数组实现。
1. 使用for循环计算前20项的和:
```c++
#include <iostream>
using namespace std;
int main() {
int sum = 0;
for (int i = 1; i <= 20; i++) {
sum += i;
}
cout << "前20项之和为:" << sum << endl;
return 0;
}
```
2. 使用数组倒序输出一个字符串:
```c++
#include <iostream>
#include <cstring>
using namespace std;
int main() {
char str[100];
cout << "请输入一个字符串:";
cin >> str;
int len = strlen(str);
for (int i = len - 1; i >= 0; i--) {
cout << str[i];
}
cout << endl;
return 0;
}
```
阅读全文