Author Topic: Simple question, needs help.....  (Read 1615 times)

Offline kevinHe

  • Single posting newcomer
  • *
  • Posts: 1
Simple question, needs help.....
« 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.

Offline frithjofh

  • Regular
  • ***
  • Posts: 373
Re: Simple question, needs help.....
« Reply #1 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.
« Last Edit: August 26, 2016, 12:25:35 pm by frithjofh »
architect with some spare time  -  c::b compiled from last svn  -   openSuSE leap x86_64  -  AMD FX-4100

Offline rlb

  • Multiple posting newcomer
  • *
  • Posts: 14
Re: Simple question, needs help.....
« Reply #2 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.
Richard Bos