operators precedence

Joined
Oct 25, 2014
Messages
12
Programming Experience
Beginner
Hi my question is that i have this piece of code for predicting the ouput


staticvoidMain(string[] args)
{
int a, b, c, x;
a
=80;
b
=15;
c
=2;
x
= a - b /(3* c)*( a + c);
Console.WriteLine(x);
Console.ReadLine();
}the possible answers to this program are

a) 78
b) -84
c) 80
d) 98

in c# when we execute the program the answers is -84 but when we follow the proper steps to simple c# arithmetic problem the answer is -125

80-15/(3*2)*(80+2);
80-15/6*82;
80-2.5*82;
80-205;
-125;


can any one explain how this is happening?
 
It's not an issue with operator precedence but rather operator implementation. In C#, when you divide an `int` by an `int` you get an `int`, NOT a `double`. That means that, where you have done this:
80-15/6*82;
80-2.5*82;
C# actually does this:
80-15/6*82;
80-2*82;
If you change the data type from `int` to `double` in your variable declaration then you will indeed get -125 as the result. More precisely, you will get -125.0, i.e. a double value.
 
Back
Top Bottom