对于跳过 c++ 的循环

For loop being skipped c++

本文关键字:循环 c++ 于跳过      更新时间:2023-10-16

我必须找到几何级数 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,然后将该结果转换为浮点数。