May be I'm asking silly question but I don't understand why this doesn't give me the output I expect (i.e 2.5
):
double x = 5/2;
Console.WriteLine(x.ToString());
May be I'm asking silly question but I don't understand why this doesn't give me the output I expect (i.e 2.5
):
double x = 5/2;
Console.WriteLine(x.ToString());
5 / 2
performs integer division no matter which type you assign it. It always disregards fractional part.
You need to use floating-point division instead.
double x = 5.0 / 2;
double x = 5 / 2.0;
double x = 5.0 / 2.0;
From /
Operator
When you divide two integers, the result is always an integer. For example, the result of 7 / 3 is 2.
From C# Specification part $7.7.2 Division operator, there 3 types of division;
And from the relevant part in integer division;
The division rounds the result towards zero, and the absolute value of the result is the largest possible integer that is less than the absolute value of the quotient of the two operands. The result is zero or positive when the two operands have the same sign and zero or negative when the two operands have opposite signs.