我必须找到几何级数的总和 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 时,程序崩溃。