十进制格式?

时间:2011-04-30 03:05:30

标签: java decimalformat

我刚刚写了一个实验室,它应该翻转两个硬币500次并计算头部和尾部被翻转的次数,并且应该计算到十分之一的百分比。我记得十进制格式的模板,但忘记了如何使用它。有人可以帮忙吗?我的计划如下:

import java.util.Scanner;
import java.text.DecimalFormat;

public class Lab97a
{
        public static void main(String [] args)
        {


        Scanner input = new Scanner(System.in);
        DecimalFormat accuracy=new DecimalFormat("0.0");

        Dice coin;
        int numCoin;
        int numHeads;
        int numTails;
        int count;
        double percentageHeads;
        double percentageTails;

        coin=new Dice(2);
        numHeads=0;
        numTails=0;

        System.out.println("A coin is tossed 500 times. The results are asfollows: ");

        for (count=1;count<=500;count=count+1)
        {
            numCoin=coin.roll();
            if (numCoin==1)
            {
                numHeads+=1;
            }
            if (numCoin==2)
            {
                numTails+=1;
            }
        }
        percentageHeads=numHeads/5;
        percentageTails=numTails/5;
        System.out.println("Heads was flipped "+numHeads+" times,
"+percentageHeads+"%.");
        System.out.println("Tails was flipped "+numTails+" times, "+percentageTails+"%");
        }
}

2 个答案:

答案 0 :(得分:2)

看起来你只需要格式化精确度,例如: accuracy.format(percentageHeads)。请参见NumberFormat.format(double)扩展的DecimalFormat

答案 1 :(得分:1)

您可以使用String.format方法作为described here

   System.out.println(String.format("Heads was flipped %d times, %.2f %%"), numHeads,percentageHeads);