Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

andren
andren
28,558 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.