Reputation: 51
My problem is too strange, Brief :
double a = 1 / 2;
MessageBox.Show(a.ToString());
It shows 0
I tried with decimal
, float
but it's always 0
Upvotes: 1
Views: 151
Reputation: 62265
you need to write :
double a= 1 / 2.0d;
By dividing int
to int
compiler produces int
result and after assigns it to double
.
It's the same like writing:
int resultInt = 1/2;
double a = resultInt;
By specifying in your operation 2.0d
you explicitly manifest your intention to produce double
after devision.
Upvotes: 11
Reputation: 234875
The division is being performed in integer arithmetic which means you will lose precision before the result is assigned to your double
type.
Promote one of the literals to a double
to force the calculation to be performed in floating point. i.e. write
double a = 1.0 / 2;
Upvotes: 5
Reputation: 107387
1
and 2
are both regarded as integer constants. The result of an int
divided by an int
is another int
, before it is cast to double
. Indicate to the compiler that at least one of the constants is double by suffixing it with d
, or providing a decimal point.
e.g.
double a = 1d/2d;
Upvotes: 4