c++ - 跳过循环 C++

标签 c++ for-loop

我必须找到几何级数的总和 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/

相关文章:

使用 C 将字符串中的所有其他字母字符更改为大写

c++ - 尝试在结构中接收模板并将其用于 std::vector

c++ - 在声明和初始化指针后,什么时候给变量字面量加上星号前缀,什么时候不用?

c++ - QDialog::accept 不响应关闭

c++ - 无限 while 循环和 for 循环有什么区别?

python - 用理解替换 Python 嵌套的 For 循环

arrays - 有没有办法从 NSManagedObject 数组中获取特定属性的字符串数组

r - K-Skip-N-Gram : generalization of for-loops in R

c++ - QTextDocument::drawContents 仅以 96 dpi 呈现

c++ - Visual Studio 2012 中的立方根函数 cbrt()