wrong result

Hello !

I wonder why i get a wrong result :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>

using namespace std;

int main()
{

    int s = 5;

    for (int i = 1; i < 1000000; ++i){


        s += i*10/5;
    }
    cout << s << endl;
}


The code will add i*10/5 to the preceding result of s.

It should get 9999999900000006 but throws -728379963

How could a negative number be throwed here ??

Any clue ?

Thanks,
Last edited on
Presumably, because you're going over the maximum possible value that can be held by an int on your platform, and the binary number being stored in your int is one that represents a negative number.

Try outputting the value of s on each iteration of the loop, and you'll be able to see where this is happening.
Solved

Thanks MikeyBoy !

replaced int with double and everything went well again :)

Thanks:
Last edited on
i would suggest that you use long int rather than double, if you really want to deal with integer numbers.
Topic archived. No new replies allowed.