Using a loop problem.

I have to make a loop for this one: [1/(2*1)] + [1/(2*2)] + [1/(2*3)] + ... +[1/(2*i)]. I've made a code like this but the result always is 0... I don't even know why :/

1
2
3
4
5
6
7
8
9
10
11
12
13
    int n;
    double sum = 0;
    cout << "Give n: ";
    cin >> n;
    
    for (int i = 1; i <= n; i++)
    {
        double m = 1/(2*i);
        
        sum += m;
    }
    
    cout << sum;
1/(2*i);Integer divsion here. Fractional part of the result is discarded.
To fix, tell compiler that you want floating point division here: 1.0/(2*i);
1 / (2 * i)
will produce an integer. Try
1.0 / (2.0 * i)

http://stackoverflow.com/questions/3602827/what-is-the-behavior-of-integer-division-in-c
Last edited on
Ahhh, thank you both.
Topic archived. No new replies allowed.