2014-01-31 16 views
0
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) 

我想弄清楚如何计算第二列的百分比到第三。如何让我的百分比在我的Dice程序中工作?

这是我的,但我知道我需要做别的。

我宁愿偏离使用该hashmap,只是使用更正确的问题。


​​

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

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); 

     } 
    } 
} 

回答

3

您使用整数算术,这意味着你的结果被在保存之前转换为int变量为percent
为了避免这种情况,只投这样的一个变量:

double percent = (double)dicer/numRol; 

由于@PaulHicks说,你真的应该由100繁殖。你可以像这样做,通过声明它作为一个浮点文字(100.0),完全避免铸造:

double percent = 100.0 * dicer/numRol; 
+1

这只会给出比例。要获得百分比值,您需要将结果乘以100. –

+0

@Keppil我的第三列仍显示为零。我用我的完整代码编辑了我的帖子。有什么我做错了吗? – Frightlin

+0

@ user3023253:试试我的第二个建议。 – Keppil

0

更改此

double percent = dicer/numRol; 

double percent = ((double)dicer/numRol)*100; 
0

切丁/由于dicer和numRol是整数,因此numRol将始终返回0,并且numRol> dicer!

为了得到一个百分比的结果,你必须改变Dicer酶的种类增加一倍,而不是INT

取代:

int dicer = sumArray[i]; 

有:

double dicer = sumArray[i]; 
+0

真棒谢谢你很多 – Frightlin

+0

欢迎您:) – Mohammed

0

或者,你可能会增加保持远离浮点数学的精度:

int percentX10 = (1000 * dicer)/numRol; 
String percentString = String.format("%d.%d", percentX10/10, percentX10 % 10); 
+0

但这有点微不足道:) –

相关问题