对于跳过 c++ 的循环
For loop being skipped c++
我必须找到几何级数 1/3 + 1/9 + 1/27 的总和......我必须以设置精度 6 输出总和。
这是我的代码:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int n;
int x = 1;
float sum = 0;
cin >> n;
for (int i = 1; i <= n; i++){
x *= 3;
sum += (float)(1/x);
}
cout << fixed << setprecision(6);
cout << "Sum of the geometric progression of the first " << n << " elements is " << sum << endl;
return 0;
}
程序总是输出 0.000000,当我尝试在 for 循环中添加测试时,程序崩溃了。
(1/x)
始终为 0,因为两个参数都int
。例如,请改用(1.0 / x)
。
因为x
是一个int
,
(1/x)
计算为整数除法,向下舍入为零。 然后将其转换为 (float)
,但它已经为零。
您可以使用(1 / (float) x)
来获得您想要的东西。
更改此行:
sum += (float)(1/x);
自:
sum += (1/(float)x);
您正在执行整数除法,结果为 0,然后将该结果转换为浮点数。
相关文章:
- 如何循环打印顶点结构
- 如何在C++中从两个单独的for循环中添加两个数组
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 正在尝试了解输入验证循环
- std::map<struct,struct>::find 找不到匹配项,但是如果我循环通过 begin() 到 end(),我在那里看到匹配项
- 循环后如何继续阅读
- Ardunio UNO解决了多个重叠的定时器循环
- Eigen如何在容器循环中干净地附加矩阵
- 在某些循环内使用vector.push_back时出现分段错误
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 为什么我的for循环不能正确获取argv
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- while循环中while循环的时间复杂度是多少
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 为什么在这个代码结束循环中没有得到结束
- 在基于范围的for循环中使用结构化绑定声明
- 用于C++中带有数组和指针的循环
- 循环中的随机函数
- 是什么阻止DOMTimerCoordinator::NextID进入无休止的循环
- 在循环C++中指定字符串之后,不会打印该字符串