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
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes – that calculation is being performed in integer arithmetic. Try this:
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
dsuffix: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:
Again, you only need to cast one of them, so this would work too:
Note that this isn’t specific to division – it affects the other arithmetic operators too.