[try Beta version]
Not logged in

 
wrong result

Jul 8, 2013 at 11:33am
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 Jul 8, 2013 at 11:34am
Jul 8, 2013 at 11:38am
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.
Jul 8, 2013 at 11:42am
Solved

Thanks MikeyBoy !

replaced int with double and everything went well again :)

Thanks:
Last edited on Jul 8, 2013 at 12:18pm
Jul 8, 2013 at 2:32pm
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.