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 回答