骰子模拟器 C++

Dice Roll Simulator C++

在 class 中,我们收到了一项任务,要编写一个模拟掷骰子(或多个)的 C++ 程序。很简单,我真的很容易做到这一点,甚至让它一次掷出 1 个以上的骰子并计算一个数字被掷出的次数(2-12,正如您将在底部的代码中看到的那样)。但是后来老师给了我们另一个作业。让程序滚动用户输入的骰子数量,根据用户输入骰子有多少面,用户希望掷骰子多少次,并且能够 "hold" 骰子,就像在游戏中一样快艇.

我和我的 class 伙伴们真的很困惑如何做到这一点,老师给我们的创建 "hold" 函数的提示涉及数组。我们很困惑,因为我们拥有的唯一数组示例是我们在 class 中所做的示例,我们制作的原始骰子模拟器作为示例并掷两个骰子等

以下是我目前拥有的代码。我知道并非我所有的变量都有目的,我尝试用数组复制我的代码下面的示例,我知道我做的不对,所以请对我放轻松。我不是要你为我做作业,我只是需要一些关于下一步该做什么以及我做错了什么的指导。带有注释标签的代码是我提到的原始 Dice Simulator,上面是我正在处理的内容。感谢任何帮助。

srand (time(NULL));
int dicenumber,diceroll,sides,rolls,rolling;
//Be able to hold, ask how many dice to roll, how many sides per die, and how many rolls
cout<<"3[1;36m How many dice would you like to roll? 3[0m \n";
cin>>dicenumber;
cout<<"3[1;36m How many sides per die? 3[0m \n";
cin>>sides;
cout<<"3[1;36m How many times do you want to roll? 3[0m \n";
cin>>rolls;

//Sets total rolls to 0
for (rolling=0;rolling<rolls;rolling++)
    diceroll=rand()%sides+1;
    cout<<diceroll;




//Initialize variables and randomness
//srand (time(NULL));
//int COUNTER,ROLLS,TOTALS[13];

        //Set totals to 0
//for (COUNTER=0;COUNTER<13;COUNTER++)
//TOTALS[COUNTER]=0;

        //Simulate 1,000,000 dice rolls
//for (ROLLS=0;ROLLS<1000;ROLLS++)
    //TOTALS[rand()%6+1+rand()%6+1]++;

        //Output the totals
//for (COUNTER=1;COUNTER<13;COUNTER++)
    //cout<<COUNTER<<" = 3[1;36m"<<TOTALS[COUNTER]<<"3[0m \n";

您可以使用 std::vector<int>int[DICE_COUNT],甚至 std::vector<Die>,创建 Die class。有很多方法可以做到这一点,但基本上可以将 array/vector 视为存储多个骰子的当前状态,然后可以在以后调用。

如果您对用户可以选择的骰子数量没有上限(或者更确切地说没有 'assumed' 上限),那么为了存储结果,您需要根据以下条件分配数组用户的输入,可以这样完成:

int *results = new int[dicenumber];
for(int i = 0; i < dicenumber; i++){
    // rolling the dice and storing the values...
    *(results+i) = rand() % sides + 1;
}// end for loop

// viewing the results...
for(int i = 0; i < dicenumber; i++){
    cout << *(results+i) << endl;
}
...
// end of program; free the memory when you're done
delete[] results;

在上面的例子中,你使用指针*results指向内存中的特定地址,其中使用new关键字为我们分配space来存储掷骰子的结果。在这种情况下,我们分配了 space 等于 int 乘以骰子数量的大小。对于 for 循环的每次迭代,我们都在递增指针,从而通过我们的数组进行索引。

但是,如果您刚刚接触数组,我发现您的教授不太可能想到指针算法。将结果存储在静态数组中要容易得多(或者至少更直观);下面是一个例子:

int results[32]; // allocated an array of size sizeof(int)*32, so space for 32 ints!
for(int i = 0; i < dicenumber; i++){
    // indexing through the array and assigning our roll...
    results[i] = rand() % sides + 1;
}// end for loop

// viewing the results...
for(int i = 0; i < dicenumber; i++){
    cout << results[i] << endl;
}// end for loop

无论如何,是的,数组是一种存储程序结果的简单方法。正如另一个答案所建议的那样,您确实可以使用 std::vector<int> 或其他一些自定义的向量 class/struct 来存储结果,但坦率地说,静态数组之外的任何东西都是过大的(至少对于编程课程而言...... .)