Why dont these equations return the same value? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why dont these equations return the same value?

https://code.sololearn.com/cS62BDOcD9kz/?ref=app

29th Aug 2021, 10:26 AM
Sheldon 10110
Sheldon 10110 - avatar
5 Answers
+ 2
You should understand the power of brackets The equation we put in the brackets are execute first Or else multiplications execute first then additions subtractions (2+4)*3 Ok let do in bracket first (2+4)==6 So 6*3 is 18 Lets do without it 2+4*3 Multiplication first so 4*3 == 12 12+2 is 14 this is called operator precedence
29th Aug 2021, 10:32 AM
Vtec Fan
Vtec Fan - avatar
+ 1
What makes you think the two expressions should result the same? int amount = 1000; int amount1 = amount * 10 / 100; // 1000 * 10 / 100 // result: 100 int amount2 = ( 10 / 100 ) * amount; // ( 10 / 100 ) * 1000 // ( 0 ) * 1000 // result: 0 10 / 100 yields 0.1, BUT since both 10 and 100 are integer literals (no decimal point), the fraction in 0.1 is ignored, and you got 0 only. This is what happens in integer division. If you did it like this ... int amount2 = (int)( 10.0 / 100 * amount ); Then you will get the same result. Why? notice there's decimal point for the 10.0 which means you are doing floating point division (rather than integer division) where you'll get 0.1 from 10.0 / 100. Multiply that 0.1 by 1000, and you'll get 100.0 (a floating point value). Then the 100.0 is casted into an integer by `(int)`, and you get 100 (an integer value), which will be assigned to variable <amount2>.
29th Aug 2021, 12:09 PM
Ipang
+ 1
Ipang aaaah I see this now.. thanks
30th Aug 2021, 9:04 AM
Sheldon 10110
Sheldon 10110 - avatar
0
Rushikesh the problem wasn't operator precedence...it was that 10/100 evaluates to 0.1 but when the value is assigned to an integer it becomes 0
30th Aug 2021, 9:02 AM
Sheldon 10110
Sheldon 10110 - avatar