c++for-loop

Geometric progression is always zero


I have to find the sum of the geometric progression 1/3 + 1/9 + 1/27 ..... and I have to output the sum with setprecision 6.

Here is my code:

#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;
}

The program always outputs 0.000000 and when I try to add a test cout in the for loop, the program crashes.


Solution

  • (1/x) is always 0, since both arguments are int. Use for example (1.0 / x) instead.