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

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

2 Answers

Pablo Rocha
Pablo Rocha
10,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 
Aaron Campbell
Aaron Campbell
16,265 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,140 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!!!