我必须找到几何级数的总和 1/3 + 1/9 + 1/27 ..... 我必须输出 setprecision 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 循环中添加一个测试 cout 时,程序崩溃了。
最佳答案
(1/x)
始终为 0,因为两个参数都是 int
。例如,使用 (1.0/x)
。
关于c++ - 跳过循环 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19717672/