Stephen D
Stephen D

Reputation: 3086

Weird Java math execution

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.

Upvotes: 2

Views: 197

Answers (2)

Frank
Frank

Reputation: 15681

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

Upvotes: 3

NPE
NPE

Reputation: 500953

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.

Upvotes: 8

Related Questions