Sean Flanagan33,219 Points
Integers and Doubles: Question 7
Hi. This question confuses me.
int a = 3; csharp> int b = 2; csharp> double c = 3.5; csharp> double y = a / b * c; csharp> y 3.5
How did it come to 3.5? a is an int. b is an int. c is a double. My calculator gave the answer 5.25. So where did the answer 3.5 come from?
Pablo Rocha10,140 Points
Hi Sean Flanagan - You have "a" and "b" defined as int. So the compiler is calculating "a / b = 1" because the result will be an int which negates the right side of the decimal. Then "1 * c = 3.5".
Define them all as double and the end result should be 5.25:
csharp> double a = 3 csharp> double b = 2 csharp> double c = 3.5 csharp> double y = a / b * c csharp> y 5.25
Alternatively, you can cast an int as a double and the compiler will work as you are expecting:
csharp> int a = 3 csharp> int b = 2 csharp> double c = 3.5 csharp> double y = (double) a / b * c csharp> y 5.25
This was all so helpful to me!!!