C# C# Basics (Retired) Perfect Integers and Doubles

Dennis Zern
Dennis Zern
813 Points

What will the answer be?

y =

int a = 3; int b = 2; double c = 3.5; double y = a / b * c;

I tried 5.25 but its not correct

1 Answer

28,342 Points

The answer is 3.5. That is to say that is how the C# code will calculate it, in reality 3 / 2 * 3.5 is of course not 3.5.

The reason why the C# code results in an incorrect answer is partly due to the fact that the equation is mixing int and double types and partly down to order of operations.

Since division and multiplication has the same priority according to the order of operations C# will solve the equation from left to right. First it divides 3 by 2, since both of these are integers the result is also cast as an integer, meaning that it takes 1.5 (which is the actual answer) and turns it into the integer 1. Then it multiplies 1 with 3.5, resulting of course in the number 3.5.