WebEinstein
WebEinstein

Reputation: 41

Java modulos and division difference

2 / 4 = 0; // it should be 0.5, but the result is 0

2 % 4 = 2 // its should be 0, cuz there are no remainders, but somehow the result is 2

Why it gives this results, what I'am doing wrong?

Upvotes: 2

Views: 102

Answers (2)

Elliott Frisch
Elliott Frisch

Reputation: 201437

The result of dividing two int(s) is an int. Change one argument to a double, like

double v = ((double) 2 / 4);
System.out.println(v);

And you'll get

0.5

Finally (for modulus), the 4 goes into 2 0 times. And, 2 - (4*0) = 2; so the modulus operation (or remainder) is correct.

Upvotes: 1

chiastic-security
chiastic-security

Reputation: 20520

For the first one: since 2 and 4 are integers, this is doing integer division, which means any fractional part is discarded. It gets rounded down. If you want to force it to be floating point, you want 2/4.0 or 2.0/4. Now one of them is a floating point double rather than an int, so the result is also a double.

For the second one: when you divide 2 by 4, you get 0 remainder 2, so the answer is 2. I suspect you're thinking of dividing 4 by 2, in which case the remainder certainly is 0, so if you try 4 % 2 you'll get 0 as the result.

Upvotes: 4

Related Questions