Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Int division: Why is the result of 1/3 == 0?

People also ask

What is the result of integer division?

The result of integer division is always an integer. Integer division determines how many times one integer goes into another. The remainder after integer division is simply dropped, no matter how big it is.

How do you explain integer division?

The % (integer divide) operator divides two numbers and returns the integer part of the result. The result returned is defined to be that which would result from repeatedly subtracting the divisor from the dividend while the dividend is larger than the divisor.

What happens when you divide an int variable by 0?

Dividing by zero is an operation that has no meaning in ordinary arithmetic and is, therefore, undefined.


The two operands (1 and 3) are integers, therefore integer arithmetic (division here) is used. Declaring the result variable as double just causes an implicit conversion to occur after division.

Integer division of course returns the true result of division rounded towards zero. The result of 0.333... is thus rounded down to 0 here. (Note that the processor doesn't actually do any rounding, but you can think of it that way still.)

Also, note that if both operands (numbers) are given as floats; 3.0 and 1.0, or even just the first, then floating-point arithmetic is used, giving you 0.333....


1/3 uses integer division as both sides are integers.

You need at least one of them to be float or double.

If you are entering the values in the source code like your question, you can do 1.0/3 ; the 1.0 is a double.

If you get the values from elsewhere you can use (double) to turn the int into a double.

int x = ...;
int y = ...;
double value = ((double) x) / y;

Explicitly cast it as a double

double g = 1.0/3.0

This happens because Java uses the integer division operation for 1 and 3 since you entered them as integer constants.


you should use

double g=1.0/3;

or

double g=1/3.0;

Integer division returns integer.