tags:

views:

369

answers:

3
+13  Q: 

1/252 = 0 in c#?

I'm doing a calc and while debugging i found this:

double num = 1/252;

when I debugged this, num is set to zero (0). Is there a reason for this? I'd like to make it the actual calculation.

Thanks

+25  A: 

Yes - that calculation is being performed in integer arithmetic. Try this:

double num = 1.0 / 252.0;

Basically, the type of the variable that the result is being assigned to doesn't affect the arithmetic operation being performed. The result of dividing one integer by another is an integer; if you want floating point arithmetic to be used, you need to make one or other of the operands a floating point type. One simple way of doing that with literals is to stick ".0" on the end. Another alternative is to use the d suffix:

double num = 1d / 252d;

Note that you only really need to make one operand a floating point value for it to work, but for clarity I'd probably do both in this case.

That's easy to do with literals of course, but for other expressions (variables, the results of method calls etc) you'd need to use a cast:

int x = 1;
int y = 252;
double num = (double) x / (double) y;

Again, you only need to cast one of them, so this would work too:

int x = 1;
int y = 252;
double num = (double) x / y;

Note that this isn't specific to division - it affects the other arithmetic operators too.

Jon Skeet
Or, if you have integer vars, cast one of them to double: (double)a / b.
Vadim Shender
@Vadim: Yes, good point - I'll edit that in.
Jon Skeet
+7  A: 

1 and 252 are both literal integers, so the calculation uses integer math. 0 is the closest integer result. Use 1.0 or 252.0 to get the proper double value.

jshier
+6  A: 

you are dividing 2 ints and casting to a double,

try

double num = 1d/252d;
Pharabus