0

サイコロを振るプログラムはほぼ完成しましたが、唯一の問題は、指定した配列のサイズが原因で、5000 を超えるサイコロを入力できないことです。単純に配列のサイズをばかげた数に増やすことができると思いますが、入力に基づいて動的にサイズ変更された配列を使用するのではなく、代わりに使用したいと思いremainingRolls.ます。

注: これは、機能する編集済みの最終的なコードです。

#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>

using namespace std;

int roller(){ // loop to simulate dice roll 
    int die1, die2;
    int total;
    die1 = rand()%6+1;
    die2 = rand()%6+1;
    total=die1+die2;
    return total;
}

int main(){
    int numberOfRolls;
    int remainingRolls;
    int eights=0; // declare counter array to hold frequencies of dice results
    int i;
    int value;
    float percentage;
    int currentRoll; // declare array for dice values

    currentRoll= 0;
    cout << "How many times will the dice be rolled?" << endl;
    cin >> remainingRolls;// user input # of dice rolls
    numberOfRolls = remainingRolls;// variable to hold number of rolls (for output)
    for (i=0; remainingRolls >0; remainingRolls--){// loop to count frequency of each value
        currentRoll = roller();// activate diceRoll function
        if (currentRoll == 8){
        eights++;
        }   
    }   
    percentage = (eights*100/numberOfRolls);
    cout << "The dice were rolled " << numberOfRolls << " times." << endl;
    cout << "The value 8 came up " << eights << " times or " << percentage << "% of the time." << endl;

    getch();
    return 0;   

}
4

2 に答える 2

4

ベクトルを使用して、必要なサイズに拡大します。ちょうどpush_back()新しいロール。

于 2012-05-26T05:45:30.603 に答える
0

配列を単純に削除できます。ループの外で配列の値にアクセスすることはないので、ローカル変数に置き換えることができます。

最初に変数int currentRollを作成し、すべての出現diceValues[i]箇所を currentRoll に置き換えます。

于 2012-05-26T05:46:22.907 に答える