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

Java代码运行时控制台无法正确显示百分比问题求助

问题根因

你的代码无法输出正确百分比的核心原因是Java整数除法的精度截断规则:

  • Java中两个int类型做除法运算时,会直接舍弃小数部分,返回int类型结果
  • 你的代码中egale是int类型,1000000是int字面量,egale / 1000000的结果会被直接截断为0,后续乘以100还是0,自然得不到正确的百分比值。

修复方案

只需要把除法运算的其中一个操作数转为浮点类型,触发浮点除法即可,比如把egale强转为double,或者将1000000写为浮点字面量1000000.0。

另外你代码里还有两处可优化的点:

  • 三个骰子相等的判断条件冗余,lancer == lancer2 && lancer2 == lancer3就足够判定三个值相等,不需要额外加lancer3 == lancer
  • 输出语句里的法语拼写有误,是sont semblables不是on été sembable,不影响逻辑运行可按需修改

修复后的完整代码如下:

import java.text.DecimalFormat;
import java.util.Random;

public class DiceTest {
    public static void exercice1() {
        int egale = 0;
        Random rand = new Random();
        System.out.println("==== Lancer d'une pièce (10 fois) =====");
        for (int i=1; i<=1000000; i++){
            int lancer = rand.nextInt(6)+1;
            int lancer2 = rand.nextInt(6)+1;
            int lancer3 = rand.nextInt(6)+1;
            if(lancer == lancer2 && lancer2 == lancer3) {
                egale++;
                System.out.println("Les dés sont semblables "+egale+ " fois");
            }
        }
        // 核心修改:把egale强转为double触发浮点除法
        double pourcentage = ((double) egale / 1000000) * 100;
        DecimalFormat df = new DecimalFormat("#.##");
        System.out.println("Les dés sont semblables "+ df.format(pourcentage) + "% du temps");
    }

    public static void main(String[] args) {
        exercice1();
    }
}

修改后运行会得到接近2.78%的结果,和三个骰子点数相同的理论概率(1/36 ≈ 2.7778%)一致,符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:15:00