我必须找到几何级数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;
}
Run Code Online (Sandbox Code Playgroud)
程序始终输出0.000000,当我尝试在for循环中添加测试cout时,程序崩溃.