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

Java三位数数字频率统计程序Bug求助:中间位为5时出错

问题排查与修复

问题根源

程序错误源于使用float类型处理数字拆分时的精度误差。float采用二进制存储,无法精确表示所有十进制小数,例如处理656这类中间位为5的数字时,计算过程中会出现类似6.56被存储为6.559999...的近似值,强制转换为int时会截断小数部分,导致拆分出的数字错位、数值异常。

修复方案

改用**整数运算(取模%和除法/)**拆分三位数,完全规避浮点数精度问题,这也是处理数字拆分的标准可靠方式。

修复后的代码

import java.util.Scanner;

public class DigitFrequency {
    public static void main(String[] args) {
        Scanner rx = new Scanner(System.in);
        int ui, troll1, troll2, troll3;
        
        System.out.println("Enter a valid three digit number to calculate the frequency of the digits in it.\n");
        ui = rx.nextInt();
        
        if (ui > 99 && ui <= 999) {
            // 用整数运算拆分三位数,避免浮点数精度问题
            troll1 = ui / 100;          // 提取百位数字
            troll2 = (ui / 10) % 10;    // 提取十位数字
            troll3 = ui % 10;           // 提取个位数字

            // 原有的频率判断逻辑保持不变
            if (troll1 == troll2 && troll1 == troll3) {
                System.out.println("The number " + troll1 + " appears three times.");
            } else if (troll1 != troll2 && troll2 != troll3 && troll1 != troll3) {
                System.out.println("The number " + troll1 + " appears one time.");
                System.out.println("The number " + troll2 + " appears one time.");
                System.out.println("The number " + troll3 + " appears one time.");
            } else if (troll1 == troll2) {
                System.out.println("The number " + troll1 + " appears two times.");
                System.out.println("The number " + troll3 + " appears one time.");
            } else if (troll1 == troll3) {
                System.out.println("The number " + troll3 + " appears two times.");
                System.out.println("The number " + troll2 + " appears one time.");
            } else if (troll2 == troll3) {
                System.out.println("The number " + troll2 + " appears two times.");
                System.out.println("The number " + troll1 + " appears one time.");
            }
        } else {
            System.out.println("The entered number is invalid");
        }
        rx.close(); // 关闭Scanner,避免资源泄漏
    }
}

关键修改说明

  • 移除了所有float类型变量,改用纯整数运算拆分数字:
    • troll1 = ui / 100:整数除法直接得到百位数字(如656/100=6)
    • troll2 = (ui / 10) % 10:先除以10得到前两位,再取模10得到十位数字(如656/10=65,65%10=5)
    • troll3 = ui % 10:取模10直接得到个位数字(如656%10=6)
  • 添加了rx.close()关闭Scanner,避免资源泄漏(可选但规范)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 10:40:34