2000字范文,分享全网优秀范文,学习好帮手!
2000字范文 > java中随机数边界问题 java 简单Dice问题(随机数的运用)

java中随机数边界问题 java 简单Dice问题(随机数的运用)

时间:2019-12-03 05:15:23

相关推荐

java中随机数边界问题 java 简单Dice问题(随机数的运用)

[java]代码库/**

* Dice Write a program that simulates rolling two dice using the following

* steps: 1. Prompt the user for the number of sides for two dice. 2. “Roll” the

* dice three times by generating a random number between 1 (inclusive) and the

* number of sides (inclusive). 3. Keep track of the sum of the rolls for each

* die and output the sum and average for each die.

*

* Sample Output: How many sides does die 1 have? 6 How many sides does die 2

* have? 20 Die 1 first roll = 5. Die 2 first roll = 14. Die 1 second roll = 1.

* Die 2 second roll = 20. Die 1 third roll = 3. Die 2 third roll = 9. Die 1

* rolled a total of 9 and rolled 3 on average. Die 2 rolled a total of 43 and

* rolled 14.333 on average.

*

* @author jianfeng

*

*/

public class Dice {

public static void main(String[] args) {

int[][] dice = new int[3][2];

int first = 6;

int second = 20;

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

dice[i][0] = (int) ((Math.random() * first) + 1); // 第一个骰子三次滚动值

dice[i][1] = (int) ((Math.random() * second) + 1);

; // 第二个骰子三次滚动值

}

// 计算总数

int sum1 = 0;

int sum2 = 0;

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

sum1 += dice[i][0];

sum2 += dice[i][1];

}

// 计算平均值

float avg1 = (float) sum1 / 3;

float avg2 = (float) sum2 / 3;

// 输出

System.out.println("How many sides does die 1 have?" + first);

System.out.println("How many sides does die 2 have?" + second);

System.out.println("Die 1 first roll = " + dice[0][0]);

System.out.println("Die 2 first roll = " + dice[0][1]);

System.out.println("Die 1 second roll = " + dice[1][0]);

System.out.println("Die 2 second roll = " + dice[1][1]);

System.out.println("Die 1 third roll = " + dice[2][0]);

System.out.println("Die 2 third roll = " + dice[2][1]);

System.out.println("Die 1 rolled a total of " + sum1 + " and rolled "

+ avg1 + " on average");

System.out.println("Die 2 rolled a total of " + sum2 + " and rolled "

+ avg2 + " on average");

}

}

[代码运行效果截图]

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。