浮动号码没有显示?

时间:2013-11-20 00:28:04

标签: java floating-point

我必须为我的java类制作一个滚动2个骰子的程序,然后比较他们观察到的外观百分比与预期的出现百分比之和。预计观察到的百分比将四舍五入为小数位。但是,每当我运行程序时,观察到的百分比总是显示为“%。2fn,[百分比]”。这是我的(公认有些混乱)代码:

import java.util.*;
public class Problem1 {

public static void main(String[] args) {
    Scanner keyboard = new Scanner(System.in);
    Random roll1 = new Random();
    Random roll2 = new Random();
    int die1;
    int die2;
    int sum;
    double zero = 0;
    double one = 0;
    double two = 0;
    double three = 0;
    double four = 0;
    double five = 0;
    double six = 0;
    double seven = 0;
    double eight = 0;
    double nine = 0;
    double ten = 0;
    double[] occurances = new double [11];
    double[] percentages = new double [11];
    percentages[0] = 2.78;
    percentages[1] = 5.56;
    percentages[2] = 8.33;
    percentages[3] = 11.11;
    percentages[4] = 13.89;
    percentages[5] = 16.67;
    percentages[6] = 13.89;
    percentages[7] = 11.11;
    percentages[8] = 8.33;
    percentages[9] = 5.56;
    percentages[10] = 2.78;
    System.out.print("How many times would you like to roll the dice? ");
    int repeat = keyboard.nextInt();
    for (int i = 0; i < repeat; i++) {
        die1 = roll1.nextInt(6);
        die2 = roll2.nextInt(6);
        sum = die1 + die2;
        if (sum == 0) {
            zero++;
            occurances[0] = zero;
        } else if (sum == 1) {
            one++;
            occurances[1] = one;
        } else if (sum == 2) {
            two++;
            occurances[2] = two;
        } else if (sum == 3) {
            three++;
            occurances[3] = three;
        } else if (sum == 4) {
            four++;
            occurances[4] = four;
        } else if (sum == 5) {
            five++;
            occurances[5] = five;
        } else if (sum == 6) {
            six++;
            occurances[6] = six;
        } else if (sum == 7) {
            seven++;
            occurances[7] = seven;
        } else if (sum == 8) {
            eight++;
            occurances[8] = eight;
        } else if (sum == 9) {
            nine++;
            occurances[9] = nine;
        } else if (sum == 10) {
            ten++;
            occurances[10] = ten;
        }//if

    }//for

    System.out.println("roll      observed      expected");
    for (int i = 0; i < occurances.length; i++) {
        float observed = (float)(occurances[i]/repeat) * 100;
        System.out.println((i+2)+"         %.2fn"+observed+"%     "+percentages[i]+"%");
    }

}

}

如何在每个预期百分比之前摆脱“%。2fn”并使其只有2位小数?我认为%.2fn是这种事情的正确表示法,但它并不适用于此。

1 个答案:

答案 0 :(得分:3)

println方法对格式化模式一无所知,例如%.2f;它认为你想要打印的文字字符串。

相反,请查看the printf method,了解格式化模式。