Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between the values of a variable

Tags:

c#

casting

I wrote a code for checking typecasting in C#. The following code:

using System;
class Convert{
    public static void Main(){
        double a=14.25,b=26.12;
        var z=(int)(a*b);
        Console.WriteLine("z= "+z);
        Console.ReadKey(true);
    }
}

Gave output:

z=372

But when i modified the code a bit then i got a big difference between the value of z earlier and after modification.

using System;
    class Convert{
        public static void Main(){
            double a=14.25,b=26.12;
            var z=(int)a*b;  // Modified part
            Console.WriteLine("z= "+z);
            Console.ReadKey(true);
        }
    }

Gave output:

z=365.68

I don't understand that why is there so much difference after removing the brackets from the original code?

like image 842
Afaq Avatar asked May 19 '26 21:05

Afaq


2 Answers

Without the outer parentheses, the (int) cast applies to a only.
Therefore, you end up multiplying a truncated integer by a normal double, and type inference turns var into double.

With the parentheses, the cast applies to the result of the multiplication. Therefore, the entire result gets truncated, and type inference turns var into int.


Thus, changing var to double would have no effect on either example. (in the second case, it would assign the truncated int to a double variable)

Changing var to int would turn the second example into a compiler error.

like image 90
SLaks Avatar answered May 22 '26 12:05

SLaks


brackets set prioryty

var z=(int)(a*b);//(a*b) cast to int
var z=(int)a*b;//a cast to int and myltiply with b
like image 41
burning_LEGION Avatar answered May 22 '26 10:05

burning_LEGION



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!