19

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

M4N
  • 94,805
  • 45
  • 217
  • 260
locoboy
  • 38,002
  • 70
  • 184
  • 260
  • 17
    That is Jon Skeet who answered your question. Go show this to all your pals. I would. :) –  Sep 01 '10 at 20:00
  • possible duplicate of [Division in c# not going the way I expect](http://stackoverflow.com/questions/2400799/division-in-c-not-going-the-way-i-expect) – H H Sep 03 '10 at 17:44

3 Answers3

31

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
  • 1,421,763
  • 867
  • 9,128
  • 9,194
9

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.

Jon Shier
  • 12,200
  • 3
  • 35
  • 37
7

you are dividing 2 ints and casting to a double,

try

double num = 1d/252d;
Pharabus
  • 6,081
  • 1
  • 26
  • 39