[英]Percentage math not coming out correctly for random dice roll
所以我有我正在处理的这段代码,除了打印/显示百分比结果外,它似乎运行正常。 当百分比相加时,我看到总数不等于 100。我觉得这可能与强制转换有关,但是,我不知道错误在哪里,并且已经多次遍历代码。 如果有人可以帮助我并给我任何关于保护结构的提示/我应该知道的任何其他菜鸟的东西,请这样做! 我是一个相当新的程序员,做这件事的时间还不到半年,所以就像我说的那样,任何提示都将不胜感激。 谢谢!
import java.util.Random;
import java.util.Scanner;
public class DiceRoller {
public static void main(String[] args) {
calculatePercentage();
}
//Get roll number from user
static int getNumOfRolls(){
Scanner input = new Scanner(System.in);
System.out.println("How many times would you like to roll the dice?");
int numOfRolls = input.nextInt();
return numOfRolls;
}
//use object from class random to assign var value from 1 - 6 inclusive
static int rollDice(){
Random rand = new Random();
int die = (rand.nextInt(6) + 1);
return die;
}
static void printPercentage(int[] dieTotal, int numOfRolls){
double totalPer = 0;
double percent = 0;
for(int i = 2; i < dieTotal.length; i++){
int curNum = dieTotal[i];
percent = ((curNum / (double)numOfRolls) * 100);
totalPer += percent;
System.out.printf("%d was rolled %.2f %% of the time. \n", i, percent);
}
System.out.println("Total percentage shown on the screen in: " + totalPer);
}
//store values of dice in an array. Call printPercent method defined above.
static void calculatePercentage(){
int numOfRolls = getNumOfRolls();
int die1 = 0;
int die2 = 0;
int[] dieTotal = new int[13];
for(int i = 0; i < numOfRolls - 1; i++){
die1 = rollDice();
die2 = rollDice();
int total = die1 + die2;
dieTotal[total]++;
}
printPercentage(dieTotal, numOfRolls);
}
}
您掷骰子的次数比请求的次数少 1。 例如,如果您输入 3,则骰子只会掷两次。 原因是你的for
循环条件:
for(int i = 0; i < numOfRolls - 1; i++){
一旦达到2
而不是3
这将停止循环。 这是一个“逐一”错误。 尝试:
for(int i = 0; i < numOfRolls; i++){
这给了我:
Total percentage shown on the screen in: 100.0
请注意,对于numOfRolls
某些值,由于浮点错误,它仍然可能不会达到 100%。 例如53
卷给了我:
Total percentage shown on the screen in: 99.99999999999999
错误在于您的calculatePercentage
函数中的for
循环条件语句。
由于您将上限设置为i < numOfRolls -1
,因此您只会获得n-1
的滚动次数。 在下面进行这些更改:
static void calculatePercentage(){
int numOfRolls = getNumOfRolls();
int die1 = 0;
int die2 = 0;
int[] dieTotal = new int[13];
for(int i = 0; i < numOfRolls; i++){
die1 = rollDice();
die2 = rollDice();
int total = die1 + die2;
dieTotal[total]++;
}
printPercentage(dieTotal, numOfRolls);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.