Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is "long x = 1/2" equal to 1 or 0, and why? [duplicate]

if I have something like:

long x = 1/2;

shouldn't this be rounded up to 1? When I print it on the screen it say 0.

like image 961
user69514 Avatar asked Feb 02 '10 20:02

user69514


People also ask

What does X != 1 mean?

x == 1) in a question. While I understand that x == 1 means x is equal to 1 , and x != 1 means x is not equal to 1 .

What is the value of 1/2 in Java?

1 and 2 are both integers, so 1 / 2 == 0 . The result doesn't get converted to double until it's assigned to the variable, but by then it's too late. If you want to do float division, do 1.0 / 2 .

Can you divide long in Java?

Java Long divideUnsigned() Method. The divideUnsigned() method of Java Long class is used to return the unsigned quotient by dividing the first argument with the second argument such that each argument and the result is treated as an unsigned argument.


2 Answers

It's doing integer division, which truncates everything to the right of the decimal point.

like image 181
tvanfosson Avatar answered Sep 23 '22 12:09

tvanfosson


Integer division has its roots in number theory. When you do 1/2 you are asking how many times does 2 equal 1? The answer is never, so the equation becomes 0*2 + 1 = 1, where 0 is the quotient (what you get from 1/2) and 1 is the remainder (what you get from 1%2).

It is right to point out that % is not a true modulus in the mathematical sense but always a remainder from division. There is a difference when you are dealing with negative integers.

Hope that helps.

like image 31
Johann Oskarsson Avatar answered Sep 21 '22 12:09

Johann Oskarsson