You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java找零计算器硬币计算失效问题求助

Fixing Your Coin Change Calculation in Java

Hey there! I see you're having trouble with the coin (decimal) part of your change calculator—let's get that sorted out. The root issue here is using double to handle currency values, which leads to floating-point precision errors that mess up your modulo and division calculations for coins.

Why the coin calculations break

Floating-point numbers like double can't represent decimal values (like 0.10 or 0.25) exactly in binary. For example, 0.1 is actually stored as an approximate value, which causes tiny inaccuracies that add up when you do modulo or division operations. That's why your paper bill calculations work (they use whole numbers, so the errors don't show up), but the coin calculations break.

The Fix: Use Integers for Cents

The simplest solution is to convert all currency values to integers representing cents (so $1.25 becomes 125 cents). This way, all your calculations are exact integer operations, no more precision bugs.

Modified Code

import java.util.*;
public class Decisions1 {
 static String taskValue = "C1";
 public static void main(String[] args) {
 // Initiate the scanner
 Scanner myInput = new Scanner(System.in);
 // Store total cost in cents to avoid precision issues
 int totalCents = 0;

 // Ask for total cost
 System.out.println("Please enter the total cost of all goods. This program will add tax and calculate the change you must give back to the customer.");
 double totalInput = myInput.nextDouble();
 totalCents = (int) Math.round(totalInput * 100);

 // Calculate 13% tax (in cents)
 int taxCents = (int) Math.round(totalCents * 1.13);

 // Store amount paid in cents
 int paidCents = 0;
 // Convert back to dollars for user-friendly display
 double taxDollars = taxCents / 100.0;
 System.out.println("You entered $" + totalInput + "\n" + "Total with tax = $" + taxDollars + "\n" + "Please enter how much cash was paid by the customer. The amount of change owed to the customer will be displayed.");
 double paidInput = myInput.nextDouble();
 paidCents = (int) Math.round(paidInput * 100);

 // Check if customer paid enough
 if (taxCents > paidCents) {
 int owedCents = taxCents - paidCents;
 double owedDollars = owedCents / 100.0;
 System.out.println("The customer still owes $" + owedDollars + "!");
 } else if (taxCents == paidCents) {
 System.out.println("The customer has paid the exact amount. You don't have to give them any change.");
 } else if (taxCents < paidCents) {
 int changeCents = paidCents - taxCents;

 // Define denominations in cents
 int oneHundred = 10000; // $100 = 10000 cents
 int fifty = 5000;
 int twenty = 2000;
 int ten = 1000;
 int five = 500;
 int toonie = 200;
 int loonie = 100;
 int quarter = 25;
 int dime = 10;
 int nickel = 5;
 int penny = 1;

 // Calculate each denomination
 int oneHundredOwed = changeCents / oneHundred;
 changeCents = changeCents % oneHundred;

 int fiftyOwed = changeCents / fifty;
 changeCents = changeCents % fifty;

 int twentyOwed = changeCents / twenty;
 changeCents = changeCents % twenty;

 int tenOwed = changeCents / ten;
 changeCents = changeCents % ten;

 int fiveOwed = changeCents / five;
 changeCents = changeCents % five;

 int tooniesOwed = changeCents / toonie;
 changeCents = changeCents % toonie;

 int looniesOwed = changeCents / loonie;
 changeCents = changeCents % loonie;

 int quartersOwed = changeCents / quarter;
 changeCents = changeCents % quarter;

 int dimesOwed = changeCents / dime;
 changeCents = changeCents % dime;

 int nickelsOwed = changeCents / nickel;
 changeCents = changeCents % nickel;

 int penniesOwed = changeCents;

 // Display final change
 double totalChangeDollars = (paidCents - taxCents) / 100.0;
 System.out.println("TOTAL CHANGE: $" + totalChangeDollars + "\n" + 
 "$100 Bill(s) = " + oneHundredOwed + "\n" + 
 "$50 Bill(s) = " + fiftyOwed + "\n" + 
 "$20 Bill(s) = " + twentyOwed + "\n" + 
 "$10 Bill(s) = " + tenOwed + "\n" + 
 "$5 Bill(s) = " + fiveOwed + "\n" + 
 "Toonie(s) = " + tooniesOwed + "\n" +
 "Loonie(s) = " + looniesOwed + "\n" + 
 "Quarter(s) = " + quartersOwed + "\n" + 
 "Dime(s) = " + dimesOwed + "\n" + 
 "Nickel(s) = " + nickelsOwed + "\n" + 
 "Pennies = " + penniesOwed);
 }
 myInput.close(); // Clean up scanner resource
 }//end main
 }// end Decisions1

Key Changes Explained

  • Cents instead of dollars: All currency values are stored as integers representing cents, eliminating floating-point errors.
  • Input conversion: User input (doubles) is converted to cents by multiplying by 100 and rounding to an integer.
  • Simplified calculations: We reuse changeCents to track remaining change after each denomination calculation, making the code cleaner.
  • Resource cleanup: Added myInput.close() to avoid scanner resource leaks (a good habit for new Java developers!).

Give this code a try—your coin change calculations should work perfectly now. As a beginner tip: never use double for currency—stick to integers or BigDecimal for exact monetary calculations.

内容的提问来源于stack exchange,提问作者Jozef Magolon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 09:12:50