Java from zero: int division drops the fraction
Dividing two ints drops the fraction. A $5.00 bill split three ways is 166 cents each, not 166.666. The program prints 166. Two cents are left over.
Piere is one of GoByte's characters. This post was drafted by AI agents in Piere's voice, then fact checked, run and edited by the GoByte team.
int is a whole number. When you divide an int by an int, the result is an int. The fraction is dropped. It is not rounded. 500 / 3 is 166. The extra two cents are gone, and no error is raised. This is the tip that saves a short bill.
Integer division is defined to drop the fraction#
When both operands of / are ints, the result is an int. 500 cents divided by 3 people is 166 cents each, remainder 2, and the remainder is discarded rather than rounded. That is a definition, not a bug in the machine. If you need the fraction, one operand has to be a floating type, and you should know that binary fractions cannot hold every decimal. The program prints 166 because both 500 and 3 are ints. The two leftover cents are still your problem.
- 500 / 3int166
public class Main {
public static void main(String[] args) {
int cents = 500;
int people = 3;
System.out.println(cents / people);
}
}
166
The types decide the division#
Both 500 and 3 are ints, so / is integer division. 500 / 3.0 is about 166.666, and a double is still the wrong place to keep money. 0.10 has no exact double. Sums drift.
Store the price as cents in an int, the way Item.cents did. 450 plus 450 is 900, and 900 is exact. When you split 500 cents three ways, each person is charged 166 and 2 cents remain. Give the remainder to one person, or keep it, but do not pretend the fraction survived.
Print the result once while you learn the operator#
The program is one division so the dropped fraction is obvious. In a larger program the same / hides inside a total. When a price looks short by a cent, look for an int divided by an int. The next lesson puts the cents in a record and adds them without ever dividing.
Your product here? Partner with us
Back to topDiscussion
No comments yet. Signed in GoByte members with a verified e-mail can join. Community guidelines
Reading is open to everyone. Commenting and voting need a GoByte account with a verified e-mail.