gpt4 book ai didi

java - 如何让我的百分比在我的 Dice 计划中发挥作用?

转载 作者:行者123 更新时间:2023-12-01 23:14:08 27 4
gpt4 key购买 nike

run:
How many dice do you want to roll: 3

How many sides on die number 1: 5
How many sides on die number 2: 4
How many sides on die number 3: 6

How many times do you want to roll: 65

Results

[3] 1 0.0%
[4] 2 0.0%
[5] 4 0.0%
[6] 6 0.0%
[7] 4 0.0%
[8] 12 0.0%
[9] 12 0.0%
[10] 8 0.0%
[11] 12 0.0%
[12] 0 0.0%
[13] 2 0.0%
[14] 2 0.0%
BUILD SUCCESSFUL (total time: 7 seconds)
<小时/>

我试图弄清楚如何计算第二列与第三列的百分比。

这是我所拥有的,但我知道我需要做其他事情。

我宁愿不使用该 HashMap ,而只是使用更正确的问题。

<小时/>
 for (int i = minRoll; i < maxRoll; i++) {
int dicer = sumArray[i];
double percent = dicer/numRol;
System.out.printf("[%d] \t %d \t %.1f%% \n", i , sumArray[i], percent);

}
<小时/>

忍者编辑:这是我的其余代码

import java.util.Scanner;

/**
*
* @author joe
*/
public class DiceSimulator {

public static void main(String[] args) {
Scanner input = new Scanner(System.in);



System.out.print("How many dice do you want to roll: ");
int amountOfDie = input.nextInt();
System.out.println("");
//declare diceArray

Die[] diceArray = new Die[amountOfDie];

//create a new Die for each reference

int maxRoll = 0;
for (int i = 0; i < diceArray.length; i++) {

System.out.print("How many sides on die number " + (i + 1) + ""
+ ": ");
int numSides = input.nextInt();
diceArray[i] = new Die(numSides);
int minRoll = amountOfDie;
maxRoll += numSides;

}
int minRoll = amountOfDie;

// int[] sumArray = new int[maxRoll + 1];//to store sum

System.out.println("");
System.out.print("How many times do you want to roll: ");
int numRol = input.nextInt();

System.out.println("\nResults");

int[] sumArray = new int[maxRoll + 1];

for (int i = 0; i < numRol; i++) {
int sum = 0;
for (Die d : diceArray) {
int roll = d.roll();
sum += roll;

}
sumArray[sum]++;
}

System.out.println("");

for (int i = minRoll; i < maxRoll; i++) {
int dicer = sumArray[i];
double percent = (dicer/numRol)*100;
System.out.printf("[%d] \t %d \t %.1f%% \n", i , sumArray[i], percent);

}
}
}

最佳答案

您正在使用整数算术,这意味着您的结果在保存到 percent 变量之前会先转换为 int
为了避免这种情况,只需转换其中一个变量,如下所示:

double percent = (double)dicer / numRol;

正如@PaulHicks所说,你真的应该乘以100。您可以这样做,通过将其声明为浮点文字 (100.0),以避免完全转换:

double percent = 100.0 * dicer / numRol;

关于java - 如何让我的百分比在我的 Dice 计划中发挥作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21473706/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com