2012-10-15 6 views
1

내 문제는 내 프로그램을 컴파일하고 실행하려고 할 때 내 코드 끝에 더 가까운 산술 문제 중 하나가 0으로 나눠진다는 것입니다. 이제 또 다른 문제가 있습니다. 사용자가 롤 수를 입력하라는 메시지가 표시 될 때마다 숫자를 입력하고 Enter 키를 누를 수 있지만 다음 줄로 건너 뛰고 아무 반응이 없습니다. 코드의 다른 부분은 발생하지 않습니다.자바에서 중첩 된 for 루프를 사용하여 확률 찾기

* 참고 *이 다음 섹션 때까지 적용되지 않습니다 때문에이 과제에 배열을 사용할 수 없습니다

.

여기 내 과제는 here입니다. 이게 내가해야할 일이야. 나는 여기서 무엇이 잘못 될지 알 수 없다. 내 수학은 정확하지만 뭔가 잘못 될 것 같습니다.

간단히 말해서, 11 개의 양면 주사위 2 개가 사용자가 입력 한 횟수만큼 "압연"되는 확률을 찾기를 원합니다. 예를 들어 3S (2 100 후 롤되는 2 개 주사위의 합을 갖는 인서트 확률) : (

사용자는 것 그것을 출력이 2S 같은 주사위가 100 회 압연 말한다하면 삽입 2 주사위의 합이 100 롤 후에 3이 될 확률) 4s : (2 주사위의 합이 100 롤 후에 4가 될 확률을 삽입하십시오.) 5s : (주사위 2 개를 합친 확률을 삽입하십시오 100 롤 이후 5)

등등. 0 numberOfRolls 시작 0 대신 1

for(int numberOfRolls = 1; numberOfRolls <= rolls; numberOfRolls++) { 

numberOfRolls 경우

public static void main(String[] args) 

{ 

    //Declare and initialize variables and objects 

    Scanner in = new Scanner(System.in); 

    Random randNum = new Random(); 




    int match = 0; //Number of times sum of dice matches the current sum 

    int die1 = 0; //Random generated numbers 
    int die2 = 0; 
    int diceTotal2 = 0; 
    int diceTotal3 = 0; 
    int diceTotal4 = 0; 
    int diceTotal5 = 0; 
    int diceTotal6 = 0; 
    int diceTotal7 = 0; 
    int diceTotal8 = 0; 
    int diceTotal9 = 0; 
    int diceTotal10 = 0; 
    int diceTotal11 = 0; 
    int diceTotal12 = 0; 

    int sumOfDice = 0; 
    double probability2 = 0.0; 
    double probability3 = 0.0; 
    double probability4 = 0.0; 
    double probability5 = 0.0; 
    double probability6 = 0.0; 
    double probability7 = 0.0; 
    double probability8 = 0.0; 
    double probability9 = 0.0; 
    double probability10 = 0.0; 
    double probability11 = 0.0; 
    double probability12 = 0.0; 


    //Input: ask user for number of rolls and number of sides on a die 

    System.out.println("Number of Rolls: "); 

    int rolls = in.nextInt(); 

    //*************************************************************************************** 

    //Using nested loops, cycle through the possible sums of the dice. 

    //Roll the dice the given number of times for each sum. 

    //Count how many times the sum of the dice match the current sum being looked for. 

    //*************************************************************************************** 


    //Loop to increment through the possible sums of the dice 

     //Loop to throw dice given number of times 

     for(int numberOfRolls = 1; numberOfRolls < rolls; numberOfRolls++) 

     { 
       die1 = randNum.nextInt(6); 
       die2 = randNum.nextInt(6); 
       sumOfDice = die1 + die2; 
       for(; ;) 
       { 

      //Check if the sum of dice is equal to the given sum 
       if(sumOfDice == 2) 

       { 
        diceTotal2++; 
        probability2 = diceTotal2/numberOfRolls; 
       } 

       else if(sumOfDice ==3) 
       { 
        diceTotal3++; 
        probability3 = diceTotal3/numberOfRolls; 
       } 

       else if(sumOfDice ==4) 
       { 
        diceTotal4++; 
        probability4 = diceTotal4/numberOfRolls; 
       } 

       else if(sumOfDice ==5) 
       { 
        diceTotal5++; 
        probability5 = diceTotal5/numberOfRolls; 
       } 

       else if(sumOfDice ==6) 
       { 
        diceTotal6++; 
        probability6 = diceTotal6/numberOfRolls; 
       } 

       else if(sumOfDice ==7) 
       { 
        diceTotal7++; 
        probability7 = diceTotal7/numberOfRolls; 
       } 

       else if(sumOfDice ==8) 
       { 
        diceTotal8++; 
        probability8 = diceTotal8/numberOfRolls; 
       } 

       else if(sumOfDice ==9) 
       { 
        diceTotal9++; 
        probability9 = diceTotal9/numberOfRolls; 
       } 

       else if(sumOfDice ==10) 
       { 
        diceTotal10++; 
        probability10 = diceTotal10/numberOfRolls; 
       } 

       else if(sumOfDice ==11) 
       { 
        diceTotal11++; 
        probability11 = diceTotal11/numberOfRolls; 
       } 

       else if(sumOfDice ==12) 
       { 
        diceTotal12++; 
        probability12 = diceTotal12/numberOfRolls; 
       } 

      }     

     } 



     System.out.println("Sum of Dice" + "   " + "Probability"); 
     System.out.println("2s: \t\t" + probability2 + "%"); 
     System.out.println("3s: \t\t" + probability3 + "%"); 
     System.out.println("4s: \t\t" + probability4 + "%"); 
     System.out.println("5s: \t\t" + probability5 + "%"); 
     System.out.println("6s: \t\t" + probability6 + "%"); 
     System.out.println("7s: \t\t" + probability7 + "%"); 
     System.out.println("8s: \t\t" + probability8 + "%"); 
     System.out.println("9s: \t\t" + probability9 + "%"); 
     System.out.println("10s: \t\t" + probability10 + "%"); 
     System.out.println("11s: \t\t" + probability11 + "%"); 
     System.out.println("12s: \t\t" + probability12 + "%"); 


     //After all throws, calculate percentage of throws that resulted in the given sum 



} //end main 
+3

참고 : 배열을 사용하면 프로그래머가 훨씬 더 짧아지고 읽기 쉬울 것입니다 ... –

+0

나는 nit-pick을 사용하지 않고 할당을 원합니다.'4. 주사위 조합의 확률을 계산하십시오. [...]. throw 횟수는이 확률에 영향을주지 않습니다. 양도인이 원한다고 생각하는 것은'4입니다. 던지기를 시뮬레이트하고 각 가능한 합계의 백분율을 표시하십시오. [...]. – brimborium

+0

어떻게 그 일을 할 수 있습니까? 무엇을 바꾸어야합니까? – user1745508

답변

1

이미 해결책을 가지고, 나는 다른 당신을 제공합니다 : 그것은 당신이 어떻게이 작업을 해결하기 위해 배열을 사용하는 방법을 보여줍니다

import java.util.Random; 
import java.util.Scanner; 

public class Main { 
    public static void main(String[] args) { 
     int nRolls = 100, nDice = 6; // default values 

     Scanner in = new Scanner(System.in); 
     System.out.print("Number of throws: "); 
     nRolls = in.nextInt(); 
     System.out.print("Number of sides on the dices: "); 
     nDice = in.nextInt(); 

     int minSum = 2, maxSum = 2 * nDice; 
     int[] hist = new int[maxSum - minSum + 1]; 

     Random rand = new Random(); 
     for (int iter = 1; iter <= nRolls; iter++) { 
      int throw1 = 1 + rand.nextInt(nDice), throw2 = 1 + rand.nextInt(nDice); 
      int sum = throw1 + throw2; 
      hist[sum - minSum]++; 
     } 

     System.out.println("Number of rolls: " + nRolls); 
     System.out.println("Number of sides of the dice: " + nDice); 
     System.out.println("Sum of Dice   Percentage"); 
     for (int i = 0; i < hist.length; i++) { 
      System.out.println(String.format(" %2d     %5.2f%%", i + minSum, hist[i] * 100.0/nRolls)); 
      // System.out.println(" " + (i+minSum) + "    " + (hist[i]*100.0/nRolls); 
     } 

     in.close(); 
    } 
} 

. 배열 내의 각 엔트리는, 대응하는 합계로 나온 throw의 수를 보관 유지합니다. 항상 2*nDice - 1 개의 합계를 가질 수 있습니다 (두 개의 오이스가있는 1에 도달 할 수 없음). 따라서 배열의 크기는 주사위의면 수에 따라 달라집니다.

그러면 모든 히스토그램 항목을 반복하고 해당 히스토그램 항목에 1을 더합니다 (히스토그램을 오프셋하므로, 은 2의 합계에 해당하며 hist[1]은 3의 합계에 해당 함).

마지막으로 백분율을 계산하면됩니다. (확률은 아닙니다. 시뮬레이션에서이 합계가 발생한 비율입니다. 롤 수가 많으면이 비율은 확률의 근사치가됩니다.)

결국에는 인쇄 만하면됩니다. . String.format 항목은 값 정렬 전용입니다.혼란 스럽다면 대신

System.out.println(" " + (i+minSum) + "    " + (hist[i]*100.0/nRolls); 

을 대신 사용하십시오.

1

변경, 0으로 나누기의 모든 부문의 운영 결과 :

여기에 지금까지 내 코드입니다.

probability2 = diceTotal2/numberOfRolls; 
+0

이제 사용자가 여러 롤을 입력하면 롤을 제외하고 나옵니다. 롤 수를 입력 한 후 터미널에서 Enter 키를 누르면 다음 줄로 넘어 가서 숫자를 계속 입력 할 수 있습니다. 프로그램에서 앞으로 나아갈 수 없습니다. – user1745508

+3

그건 완전히 별개의 문제입니다. 나는 당신이 문제를 가지고 있고 새로운 질문으로 게시하고있는 라인에 당신의 질문에있는 코드를 정리할 것을 제안 할 것이다. – kosa

관련 문제