为了账号安全,请及时绑定邮箱和手机立即绑定

如何计算时间总和=7的次数?

如何计算时间总和=7的次数?

慕仙森 2023-01-05 17:22:07
我必须编写程序来掷 2 个骰子 100 次,并计算总和等于 7 的次数。我试着做一个循环计数来计算总和 = 7,但我认为我在逻辑上偏离了某个地方。 //    int i = 0;       No. of rolls //    int count = 0;   No. of rolls = to 7    for (int i = 0; i <= 100; i++){        int dice1 = randomGenerator.nextInt(7);        int dice2 = randomGenerator.nextInt(7);        int sum = (dice1 + dice2);        System.out.println(dice1 + ", " + dice2 + ", total: " + sum + " roll: " + i);    }    for (int count = 0; count++) {        System.out.println(count);    }    System.out.println("Total number of time sum equaled 7 was " + count);我得到了随机掷骰、掷骰数和骰子总和,只需要弄清楚如何添加总和 = 7 计数,我就卡住了。
查看完整描述

3 回答

?
潇湘沐

TA贡献1816条经验 获得超6个赞

这是另一个使用流的答案


 public static void main(String[] args){

      Random rng = new Random();

      long result = IntStream

          .generate(() -> rng.nextInt(6) + rng.nextInt(6) + 2)

          .limit(100)

          .filter(x -> x == 7)

          .count();

      System.out.println("Total number of time sum equaled 7 was " + result);

}



查看完整回答
反对 回复 2023-01-05
?
慕妹3146593

TA贡献1820条经验 获得超9个赞

使用 Java 8,程序将如下所示:


public class Dice

{

    static int count = 0;

    static Random ran = new Random();

    public static void main(String[] args)

    {

        IntStream.rangeClosed(1, 100). // iterates 1 to 100

            parallel().// converts to parallel stream

            forEach(i -> {

                rollDiceAndCheckIfSumIs7();

            });// prints to the console

        System.out.println("Out of 100 times, total number of times, sum was 7 is :" + count);


    }


    private static void rollDiceAndCheckIfSumIs7()

    {

        int dice1 = ran.nextInt(7);

        int dice2 = ran.nextInt(7);

        count += (dice1 + dice2 == 7) ? 1 : 0;

    }

}


查看完整回答
反对 回复 2023-01-05
?
www说

TA贡献1775条经验 获得超8个赞

只需将您的替换for (int count = 0; count++) { ... }为if (sum==7) count++并将其放在后面int sum = (dice1 + dice2);


如果在 100 个双掷骰子的循环中总和为 7,则这会增加计数。


要删除错误的骰子范围(0-7,请参阅评论@Robby Cornelissen)只需执行randomGenerator.nextInt(6)+1.


    int count = 0; //  No. of rolls = to 7


    for (int i = 0; i <= 100; i++){

        int dice1 = randomGenerator.nextInt(6)+1;

        int dice2 = randomGenerator.nextInt(6)+1;

        int sum = (dice1 + dice2);

        if (sum==7) count++;

        System.out.println(dice1 + ", " + dice2 + ", total: " + sum + " roll: " + i);

    }


    System.out.println("Total number of time sum equaled 7 was " + count);


查看完整回答
反对 回复 2023-01-05
  • 3 回答
  • 0 关注
  • 108 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信