Code::Blocks

User forums => General (but related to Code::Blocks) => Topic started by: kevinHe on August 26, 2016, 09:25:48 am

Title: Simple question, needs help.....
Post by: kevinHe on August 26, 2016, 09:25:48 am
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.
Title: Re: Simple question, needs help.....
Post by: frithjofh on August 26, 2016, 11:59:26 am
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.
Title: Re: Simple question, needs help.....
Post by: rlb on August 30, 2016, 02:06:56 pm
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 (https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html).