输入正整数 n,输出 2/1 + 3/2 + 5/3 + 8/5 + 13/8 + ... 的前 n 项的值,精确到小数点后三位,c语言
时间: 2023-12-12 20:11:22 浏览: 27
#include <stdio.h>
int main()
{
int n;
scanf("%d", &n); // 输入n
double a = 2, b = 1; // 初始值
for(int i = 1; i <= n; i++)
{
printf("%.3f ", a / b); // 输出结果,保留3位小数
double c = a + b; // 下一个分子
b = a; // 下一个分母
a = c; // 下一个分子
}
return 0;
}
相关问题
编写一程序,输入一个正整数n,计算2/1+3/2+5/3+......的前n项之和。
好的,这是一个求和问题,我可以帮你解决。以下是程序的代码:
```
#include <stdio.h>
int main()
{
int n;
double sum = 0;
double numerator = 2;
double denominator = 1;
printf("请输入一个正整数n:");
scanf("%d", &n);
for (int i = 1; i <= n; i++)
{
sum += numerator / denominator;
numerator += 1;
denominator += 1;
}
printf("2/1 + 3/2 + 5/3 + ... 的前%d项和为%.2f", n, sum);
return 0;
}
```
输入一个正整数n,程序就会计算 2/1 3/2 5/3 ......的前n项之和,并输出结果。如果你有其他问题,可以问我哦。
输入正整数n 输出H(n)=1+1/2+1/3+....+1/n的值,保留3位有效数字
这道题目需要计算H(n)=1+1/2+1/3+...+1/n的值,保留3位有效数字。可以使用循环来计算每个数的倒数,并将它们相加。下面是一个示例代码:
```
#include <stdio.h>
int main() {
int n;
float sum = 0.0;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
sum += 1.0 / i;
}
printf("%.3f", sum);
return 0;
}
```
如果需要处理多组数据,可以使用while循环来读取每组数据,并在每次循环结束后清空sum变量。下面是一个示例代码:
```
#include <stdio.h>
int main() {
int n;
while (scanf("%d", &n) != EOF && n != 0) {
float sum = 0.0;
for (int i = 1; i <= n; i++) {
sum += 1.0 / i;
}
printf("%.3f\n", sum);
}
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)