Home > Java > javaTutorial > body text

Why Does Integer Division in Java Produce Unexpected Results?

Susan Sarandon
Release: 2024-11-16 06:17:03
Original
517 people have browsed it

Why Does Integer Division in Java Produce Unexpected Results?

Integer Division: Understanding the Unexpected Behavior

In Java, integer division performs division between two integer values, discarding the fractional part of the result. This behavior can lead to unexpected outcomes, as demonstrated in the following code:

int quantity = 6800;
int standard = 500;
float res = quantity / standard;
Copy after login

Expected Result: 13.6

Actual Result: 13.0

One explanation for this discrepancy lies in the integer division being performed. Integer division truncates the result, resulting in the loss of the fractional part. To obtain the correct result, we need to force the division to be treated as a floating-point division.

This can be achieved by casting the numerator to float explicitly:

float res = (float) quantity / standard;
Copy after login

Alternatively, if dealing with literals, we can append the 'f' suffix to the denominator to indicate a float:

float res = 6800f / 500;
Copy after login

By using float-division, we prevent integer division and preserve the fractional part of the result. This approach will consistently yield the expected result: 13.6.

The above is the detailed content of Why Does Integer Division in Java Produce Unexpected Results?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template