2014-01-31 4 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) 

Я пытаюсь выяснить, как вычислить процент от 2-го столбца в третий.Как получить процент от работы в моей программе Dice?

Вот что у меня есть, но я знаю, что мне нужно сделать что-то еще.

Я предпочел бы отклониться от использования этой хэш-карты и просто использовать более правильную проблему.


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

     } 

Ninja Edit: Вот остальная часть моего кода

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 всегда будет возвращать 0, так как dicer и numRol являются целыми числами, а numRol> dicer!

Чтобы получить процентный результат, вы должны изменить тип Dicer удвоится вместо Int

заменить:

int dicer = sumArray[i]; 

с:

double dicer = sumArray[i]; 
+0

AWESOME THANK YOU SOOO MUCH – Frightlin

+0

Вы приветствуетесь :) – Mohammed

0

В качестве альтернативы, можно увеличить точность, избегая математики с плавающей запятой:

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

Но это немного тривиально :) –

 Смежные вопросы

  • Нет связанных вопросов^_^