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

编写最少硬币找零Java代码遇结果异常及打印问题求助

问题分析与修复方案

核心问题点

  • 浮点数精度陷阱:用double处理货币金额会出现精度丢失(比如0.29可能存储为0.2899999999999999),导致循环无法正常终止或计算错误。
  • 面值判断逻辑错误:
    • 镍币(nickel)实际面值是0.05美元,代码里误写为0.5,完全不符合实际。
    • 便士(penny)实际面值是0.01美元,代码里误写为0.1,导致小金额无法正确计数。
    • 面值判断顺序错误:0.5的判断放在0.10之后,永远不会触发,因为0.10的条件会先匹配所有大于等于0.1的金额。
  • 字符串语法错误:System.out.print里的字符串直接换行,不符合Java语法规范,会导致编译报错。

修复后的代码(保留原模板结构,仅修正逻辑错误)

import java.util.Scanner;

class Main {

    public static void main(String[] args) {
        int quarters = 0;
        int dimes = 0;
        int nickels = 0;
        int pennies = 0;
        //prompt the user for a monetary input
        Scanner sc = new Scanner(System.in);
        double changeToGive = 0;
        
        do {
            //if the user gave us a negative dollar amount
            if(changeToGive < 0)
                System.out.println("Dollar amounts must be positive.");
            
            //if the current amount is zero dollars
            else if(changeToGive == 0)
                System.out.println("How much change do you need to pay out?");
            
            // while the user's input is not a valid double, prompt again
            while (!sc.hasNextDouble()) {
                System.out.println("Invalid input.  How much change do you need to pay out?");
                sc.next(); // this is important!
            }
            
            //if the user entered a valid double, assign it to changeToGive
            changeToGive = sc.nextDouble();
        } while (changeToGive <= 0); //if the user entered a valid double but it was negative, do it all again

        // 转换为整数分,彻底避免浮点数精度问题
        int cents = (int) Math.round(changeToGive * 100);
        
        while (cents > 0){ 
            if (cents >= 25){
                cents -= 25;
                quarters++;
            }else if (cents >= 10){
                cents -= 10;
                dimes++;
            }else if (cents >= 5){
                cents -= 5;
                nickels++;
            }else if (cents >= 1){
                cents -= 1;
                pennies++;
            }
        }
        System.out.print("Your change is:\n"
                + quarters + " quarters\n"
                + dimes + " dimes\n"
                + nickels + " nickels\n"
                + pennies + " pennies\n");
    }
}

关键修复说明

  1. 替换浮点数为整数计算:将金额转换为整数分(Math.round(changeToGive * 100)),彻底规避浮点数精度丢失问题。
  2. 修正面值数值:把nickels的判断条件改为>=5(对应0.05美元),pennies改为>=1(对应0.01美元),匹配实际硬币面值。
  3. 调整判断顺序:保持从大面值到小面值的判断逻辑,确保优先使用大面值硬币,满足「最少数量找零」的需求。
  4. 修复字符串换行:用\n替代直接换行,符合Java字符串语法规范。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 17:33:01