News:

Accounts with zero posts and zero activity during the last months will be deleted periodically to fight SPAM!

Main Menu

Simple question, needs help.....

Started by kevinHe, August 26, 2016, 09:25:48 AM

Previous topic - Next topic

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

#1
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.
architect with some spare time  -  c::b compiled from last svn  -   openSuSE leap x86_64  -  AMD FX-4100

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.
Richard Bos