User forums > General (but related to Code::Blocks)

Simple question, needs help.....

(1/1)

kevinHe:
recently, I updated my Codeblocks, but when I executed the code simple as below, (Error occurs: )

double a, b;
cin >> a; // like 0.08;
cin >> b; // like 2;
int n = (b-a)*100;
cout << n;
//n is supposed to be 192 instead of getting 191 from the codeblocks.
I spent long time, couldnt find it out. please, who knows it, give me a hint or tell me the answer.

frithjofh:
sorry to tell you this, but your problem is in no way related to codeblocks, but rather a programming beginners issue.

the observed behavior is due to the way doubles work and how doubles get truncated to int. try changing the type of n to double.

but you are in the wrong place for problems as these, as i stated above already.

rlb:
frithjofh is right, and there's a very famous paper about this which you should read right now: What Every Computer Scientist Should Know About Floating Point Arithmetic, by David Goldberg; https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html.

Navigation

[0] Message Index

Go to full version