簡體   English   中英

為什么輸出總是0.0?

[英]Why is the output always 0.0?

//creates SevenTally class
public class SevenTally{

    private int count;

    public SevenTally(int diceCount){
        this.count = diceCount;
    }

    //creates experiment method
    public boolean experiment(){
        int winCount = 0;
        //creates array of dice rolled according to input
        int[] diceRolls = new int[count];
        //assigns random value from 1 to 6 to each array value
        for(int x = 0; x < diceRolls.length; x++) {
            diceRolls[x] = (1 + (int)(6 * Math.random()));
            for(int n = 0; n < diceRolls.length; n++) {
                for(int m = n + 1; m < n; m++){
                    //checks for two dice in the total rolls that sum to 7
                    if (diceRolls[n] + diceRolls[m] == 7)
                        winCount++;
                }
            }
        }
        if (winCount > 0)
            return true;
        else
            return false;
    }
}

問題似乎出在 for 循環數組上。 我只測試了代碼的那一部分,它正確地將值輸入到我的數組中,但是當我將整個內容放在一起時,我認為退出循環后數組為空或為空。

這是類驅動程序:

import java.util.Scanner;

public class SevenDriver{    

    public static void main(String[] args){      
        System.out.println("Enter number of dice to toss");     
        Scanner s = new Scanner(System.in);      
        int diceCount = s.nextInt(); 
        SevenTally t = new SevenTally(diceCount);
        int experiments = 1000000;
        int wins = 0;

        for(int j = 0; j < experiments; j++)
            if(t.experiment()) wins++;

        System.out.println((double)wins/experiments);
    } 
}

你寫了

for(int m = n + 1; m < n; m++)

mn+1開始,並且循環應該在m<n運行,那么就沒什么可做的了。 這個應該有效:

for(int m = n + 1; m < diceRolls.length; m++)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM