2.分别用while和for循环编程,实现求一下数列前20项之和 2/1, 3/2, 5/3, 8/5, 13/8, ……
时间: 2023-12-13 13:32:47 浏览: 126
Java基础编程:求出一个数列的前20项之和
以下是使用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;
}
```
阅读全文