2

I have an weird issue. I'm trying to store the result of an equation into a double variable.

double s = (((100 + 1)*(1/3))/100 + (1/3));

This returns a value a 0 rather than .67 (the correct value calculated from a calculator). Any reason why this could happen?

Note: A solution of saying that I could just make s = .67 is not a solution,

Thanks in advance.

2
  • 1
    If you add d after all your numbers, eg 100d, you'll use floating point operations, not integer ops. Commented Mar 24, 2013 at 14:21
  • As it is already answered, I am just adding a side-note that if you want precise value of 0.67 unlike something like 0.669999999999 you should use BigDecimal. stackoverflow.com/questions/322749/… Commented Mar 25, 2013 at 13:57

2 Answers 2

8

The following uses integer (i.e. truncating) division, the result of which is zero:

1/3

To get floating-point division, turn either of the argument into a double, e.g.

1.0/3

Thus, the overall expression becomes:

double s = (((100 + 1)*(1./3))/100 + (1./3));

1. is the same as 1.0. Other ways to express the same number as a double are 1d and 1D.

The above expression evaluates to 0.6699999999999999.

Sign up to request clarification or add additional context in comments.

1 Comment

Yes, I don't know how I let this slip. Thanks so much. It's been bugging me for quite some time.
3

The compiler sees your numers as int's..

try like this:

double s = (((100d + 1d)*(1d/3d))/100d + (1d/3d));

now the result will be:

0.6699999999999999

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.