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

我必须编写程序来掷 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 计数,我就卡住了。


慕仙森
浏览 110回答 3
3回答

潇湘沐

这是另一个使用流的答案&nbsp;public static void main(String[] args){&nbsp; &nbsp; &nbsp; Random rng = new Random();&nbsp; &nbsp; &nbsp; long result = IntStream&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .generate(() -> rng.nextInt(6) + rng.nextInt(6) + 2)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .limit(100)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .filter(x -> x == 7)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .count();&nbsp; &nbsp; &nbsp; System.out.println("Total number of time sum equaled 7 was " + result);}

慕妹3146593

使用 Java 8,程序将如下所示:public class Dice{&nbsp; &nbsp; static int count = 0;&nbsp; &nbsp; static Random ran = new Random();&nbsp; &nbsp; public static void main(String[] args)&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; IntStream.rangeClosed(1, 100). // iterates 1 to 100&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; parallel().// converts to parallel stream&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; forEach(i -> {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; rollDiceAndCheckIfSumIs7();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });// prints to the console&nbsp; &nbsp; &nbsp; &nbsp; System.out.println("Out of 100 times, total number of times, sum was 7 is :" + count);&nbsp; &nbsp; }&nbsp; &nbsp; private static void rollDiceAndCheckIfSumIs7()&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; int dice1 = ran.nextInt(7);&nbsp; &nbsp; &nbsp; &nbsp; int dice2 = ran.nextInt(7);&nbsp; &nbsp; &nbsp; &nbsp; count += (dice1 + dice2 == 7) ? 1 : 0;&nbsp; &nbsp; }}

www说

只需将您的替换for (int count = 0; count++) { ... }为if (sum==7) count++并将其放在后面int sum = (dice1 + dice2);如果在 100 个双掷骰子的循环中总和为 7,则这会增加计数。要删除错误的骰子范围(0-7,请参阅评论@Robby Cornelissen)只需执行randomGenerator.nextInt(6)+1.&nbsp; &nbsp; int count = 0; //&nbsp; No. of rolls = to 7&nbsp; &nbsp; for (int i = 0; i <= 100; i++){&nbsp; &nbsp; &nbsp; &nbsp; int dice1 = randomGenerator.nextInt(6)+1;&nbsp; &nbsp; &nbsp; &nbsp; int dice2 = randomGenerator.nextInt(6)+1;&nbsp; &nbsp; &nbsp; &nbsp; int sum = (dice1 + dice2);&nbsp; &nbsp; &nbsp; &nbsp; if (sum==7) count++;&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(dice1 + ", " + dice2 + ", total: " + sum + " roll: " + i);&nbsp; &nbsp; }&nbsp; &nbsp; System.out.println("Total number of time sum equaled 7 was " + count);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java