Decimal Format?
I just wrote a lab that is supposed to flip two coins 500 times and count how many times heads and tails were flipped and is supposed to calculate the percentage to the tenth. I remember the template for Decimal formatting, but forgot how to use it. Can somebod开发者_StackOverflow中文版y help? My program is as follows:
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+"%");
}
}
It looks like you just need to format the accuracy with e.g. accuracy.format(percentageHeads)
. See NumberFormat.format(double)
that DecimalFormat
extends.
You can use the String.format method for this, as described here:
System.out.println(String.format("Heads was flipped %d times, %.2f %%"), numHeads,percentageHeads);
精彩评论