Please look at the picture
Wrong answer
Right answer
The first which I used the variable i, and I get the wrong answer
The second which I did not use i, the result is right.
My compiler is MinGW GCC 4.7.2 32-bit, and my computer is win10 64-bit.
I feel very strange about the different results, Is this loss of accuration?
this is my file after using gcc test.cpp -S
the first https://paste.ubuntu.com/p/TXjCPyWC9G/
the second https://paste.ubuntu.com/p/FJXQDbyRFq/
Thanks in advance, by the way, forgive my poor english..
Asked
Active
Viewed 50 times
-6

Meepo
- 3
- 2
-
6Don't post text as images.Copy and paste it into the question instead. – nwp Mar 10 '18 at 09:21
-
I can't paste it into the question because of my level – Meepo Mar 10 '18 at 09:57
-
1@Meepo Sure you can. Copy-pasting code is the same as writing text, and you already did that. You might not able to post images in your question, but no-one is asking you to do that. – Algirdas Preidžius Mar 10 '18 at 11:19
-
I copied the essential code lines into the question, so when the edit is reviewed I hope they will be visible. – Renardo Mar 10 '18 at 11:21
-
Though I only copied text from the images to the question text, my edit was rejected. So I put a summary of the OP's code into my answer. – Renardo Mar 10 '18 at 11:47
-
The numbers 0.1, 0.2, and 0.3 looks familiar after reading this question: [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Bo Persson Mar 10 '18 at 11:50
-
1Posting code or error messages as screenshots is a bad habit people have been picking up a lot in the last one or two years. I've also noticed it at work, in e-mails by co-workers. It is extremely annoying and frustrating; perhaps it's the bad influence of "social media" where you upload photos of stuff all the time? In any case, stop doing it. Use **text**. – Christian Hackl Mar 10 '18 at 12:30
1 Answers
0
First, I summarize the two ways of computing the same numerical expression (given in images by the OP):
Correct result (“Right answer”, 9255):
int tmp = 10000 - (10000 - 8000) * 0.2 - 1500 * 0.03 - 3000 * 0.1;
Wrong result (“Wrong answer”, 9254):
int i = 10000;
int tmp = i - (i - 8000) * 0.2 - 1500 * 0.03 - 3000 * 0
The expression without the variable (“Right answer”) is computed at compile time (optimization, to save runtime), the expression with the variable i
(“Wrong answer”) is computed at runtime. Obviously the compiler and the compiled program use different arithmetics (different rounding). (The number 0.1
has no exact binary floating point representation, so rounding is necessary.)
I cannot say why these two systems use different rounding. When I compile your “Wrong” example with gcc
on my machine it yields the right answer.

Renardo
- 499
- 4
- 13