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");

}

}

[代码运行效果截图]

7a82d6b6f20eb8bf6c434b59f95be620.png

694748ed64b9390909c0d88230893790.png

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值