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

Java直方图生成代码求助:输入数值无输出问题排查

问题分析与解决

为什么输入13.5没有输出?

你代码里的int roundNum = (int)(num);是强制类型转换,并非四舍五入操作。对于13.5来说,强制转int会直接截断小数部分,得到13,但你的if判断里没有处理roundNum等于13的情况,所以程序没有任何输出。

另外,你想要的是对数值四舍五入取整,强制转换做不到这点,得用Math.round()方法,它会把double值四舍五入为最接近的整数。

修正后的代码

基础修正版(解决当前输入无输出问题)

把强制转换替换为Math.round(),并补充13的判断逻辑:

public class Histogram
{
    public static void main(String args[]) 
    {
      histogram obj = new histogram();
      obj.histogram(13.5);
    }
}

class histogram
{
    public void histogram(double num)
    {
        // 用Math.round实现四舍五入,返回long类型,转成int
        int roundNum = (int)Math.round(num);
        if (roundNum == 14)
        {
            System.out.println("**************" + num);
        }
        if (roundNum == 13)
        {
            System.out.println("*************" + num);
        }
        if (roundNum == 3)
        {
            System.out.println("***" + num);
        }
        if (roundNum == 16)
        {
            System.out.println("****************" + num);
        }
        if (roundNum == 0)
        {
            System.out.println("" + num);
        }
        if (roundNum == 1)
        {
            System.out.println("*" + num);
        }
    }
}

此时输入13.5,roundNum会被计算为14,就能输出对应数量的星号。

优化版(动态生成星号,无需逐个判断)

上面的写法只能处理固定几个数字,扩展性差。可以用循环动态生成对应数量的星号,适配任意正整数结果:

public class Histogram
{
    public static void main(String args[]) 
    {
      Histogram obj = new Histogram();
      obj.histogram(13.5);
    }

    public void histogram(double num)
    {
        int roundNum = (int)Math.round(num);
        // 动态拼接对应数量的星号
        StringBuilder stars = new StringBuilder();
        for (int i = 0; i < roundNum; i++) {
            stars.append("*");
        }
        // 输出星号与原始数值
        System.out.println(stars + " " + num);
    }
}

这个版本不管输入什么数值,只要四舍五入后是正整数,都能自动生成对应星号,无需编写大量if判断。另外,Java类名建议首字母大写,优化版已调整为符合规范的命名方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 03:01:41