Click here to Skip to main content
15,892,005 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
when i made this program its showing 58 , when i compile its but its ans is 59 . Its not following bodmas is it?
program is below :=

plas help and a

What I have tried:

C++
#include <iostream>

using namespace std;

int main()
{

int x=3;
float y=5.6;
x=x+10*y;
cout<<x;
    return 0;
}
Posted
Updated 24-Dec-16 4:14am
v3
Comments
Philippe Mori 24-Dec-16 10:06am    
Floating point values are not exact. So your have to properly round them when converting to avoid something like 58.9999 to be truncated to 58. As far as I known, the FPU will round numbers but C/C++ will truncate them.

59 is the correct answer, isn't it?
The behaviour has nothing to do with bodmas violation, it follows from rounding rules of IEEE754[^], I believe.
 
Share this answer
 
Probably, it depends on the compiler and system you are using: when I try it, I get 59.
The problem may be happening because you are mixing data types:
C++
x=x+10*y;
  ^  ^ ^
  |  | |
  |  | ---- float
  |  ------ integer
   -------- integer
When you multiply 10 * y there are two ways the system can do it: convert the integer 10 to a float and then multiply, or convert the float to a integer and then multiply - and that may produce different results if the conversion of "5.6" is rounded or truncated. Rounding would give you 6, truncation would give you 5, so you could conceivably get 50, 56, or 60 as an integer result. Which means you could get a final value of 53, 59, or 63 - but it's very unlikely that you would get 58.
Except...it could be a precision problem: Float Precision–From Zero to 100+ Digits | Random ASCII[^]
Try making everything floating point:
C++
float x = 3.0;
float y = 5.6;
x = x + 10.0 * y;
cout << x;
And I suspect your problem will just go away...
 
Share this answer
 
Comments
CPallini 24-Dec-16 11:06am    
In the expression, the computation shall happen this way:
an implicit conversion to float
http://en.cppreference.com/w/c/language/conversion
of all the operands is performed. Eventually the result is cast to int.
Afzaal Ahmad Zeeshan 24-Dec-16 14:10pm    
5ed.
floats do not store exact values, that is your problem.
Try:
C++
x=round(x+10*y);

With floats, 5.6 is something like 5.599999...
and x+10*y gives 58.99999... which is converted to 58 when stored in x.
round - C++ Reference[^]
 
Share this answer
 
v2
Comments
CPallini 24-Dec-16 11:14am    
On my system 5.6 is 0x40b33333, which problably resembes 5.5999..
However 5.6*10 is 0x42600000 which is 56 (exponent 6, mantissa = 0.111B)
That is, according to IEEE754 rules, the result is rounded.
Afzaal Ahmad Zeeshan 24-Dec-16 14:10pm    
5ed.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900