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

Sean Flanagan
Sean Flanagan
33,235 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?

2 Answers

Pablo Rocha
Pablo Rocha
10,142 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 
Aaron Campbell
Aaron Campbell
16,267 Points

I thought in order of operations, it would be Parenthesis, Exponent, Multiply, Divide, Add, Subtract.

In this case, the b*c should be the first one, because it's Multiply, then you divide 3 by that result. Or did I miss something?

Pablo Rocha
Pablo Rocha
10,142 Points

Order of operations does not place multiply or divide before one or the other. It just goes from left to right. Same thing for add and subtract.

Parenthesis, Exponent, Multiply/Divide, Add/Subtract

This was all so helpful to me!!!