Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected result while dividing int by int and storing result into double [duplicate]

I'm having a weird problem.

This code simply divides an int by another int, stores result in a double variable and prints it:

int a = 200;
int b = 557;

double divisionResult = a / b;

System.out.println("Result: " + divisionResult);

After executing this code, the output is:

Result: 0

This is weird, because 200/557 is 0.3590664272890485

I noticed that if i cast a and b to double in the division line

double divisionResult = (double) a / (double) b;

It works perfectly.

Why do i have to cast my variables to double to get the real division result?

like image 621
BackSlash Avatar asked May 02 '13 11:05

BackSlash


People also ask

What happens when an int is divided by a double?

The result of dividing a double by a double is a double. However, if both expressions have type int, then the result is an int.

What is unusual about the result of integer division?

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. because 4 goes into 7 just once. The result is not rounded up to 2.

What happens when you have an int divided by an int Java?

When dividing an integer by an integer, the answer will be an integer (not rounded). When an operation involves two types (as the mixed division shown above), the smaller type is converted to the larger type. In the case above, the integer 5 was converted to a double type before the division occurred.

How does C++ handle integer division?

If both operands are integers, C++ performs integer division. That means any fractional part of the answer is discarded, making the result an integer. If one or both operands are floating-point values, the fractional part is kept, making the result floating-point.


1 Answers

Because in integer division, if the answer is not a perfect integer, the digits after the decimal point will be removed (integer division yields integer value).

Note that you don't have to cast the both integers, you can cast only one, the second will be implicitly converted.

Why after the cast it works?

Because cast has higher precedence than /. So first it cast, then it divides. If this were not the case, you would get 0.0.

like image 177
Maroun Avatar answered Nov 02 '22 21:11

Maroun