用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - java代码库

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

2012-09-19 作者: 神马举报

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

[代码运行效果截图]


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


网友评论    (发表评论)


发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...