【发布时间】:2018-12-17 19:16:30
【问题描述】:
我的教授要求我们编写一个程序:
使用循环模拟一对骰子滚动一千次(这里我认为 for 循环会很有用)。
每次迭代时,循环需要计算每个值从 2 到 12 的次数(这里我认为 if/else 语句会适用)
当循环结束时,必须显示每个值(从 2 到 12)出现的次数。
他的作业结构如下:
他希望我们使用一个进入 1000 次 for 循环的函数,每个函数调用两次调用另一个函数(模拟掷两个骰子)。
让我解释一下我设法放下了什么
//
// main.cpp
// RollingDice
#include <iostream>
#include <ctime>
using namespace std;
int roll();
int rollDice();
int main(int argc, const char * argv[])
{
for (int i = 1; i < 1000; i++)
{
rollDice(); //This is the function that is supposed to call the roll();
//function two times. This makes sense to me that TWO DICE
//are being rolled 1000 times.
}
int result; //These two statements was where I was just hoping for something
//to work. I put these variable statements outside of the for
//loop because I was thinking that the int rollDice(); function
//definition(below) wouldn't know how to use it otherwise. I
//know that doesn't make sense, but I just can't explain why.
result = rollDice();
}
int roll()
{ //This function was provided to us by my professor.
static bool randomInitialized = false;
int points;
if (!randomInitialized)
{
srand((unsigned int) time(NULL));
randomInitialized = true;
}
points = (rand() % 6) + 1;
return points;
}
int rollDice()
{ //This I wrote myself. I'm imagining this is how you call a function twice.
//The return statement in this function was my attempt of returning the sum
//of the values of the two dice.
roll();
roll();
return result;
}
除了程序的这一部分不起作用之外,我仍然遇到的另一个问题是确定一种方法来为每个发生的值设置一个计数器(但是,我想象程序的该部分属于 for 循环。那就是我所知道的一切。)。从昨天开始,我就对这个计划进行了深入的思考。我今天回到它希望一个新的头脑能解决它,但我仍然在挣扎。非常感谢任何和所有帮助。
【问题讨论】:
-
与其说所有
randomInitializedrigamarole,不如在main的第一行调用srand? -
计数器可以是一个 int 数组,只增加数组[result]
-
@FeiXiang 评论补充:学习使用数组。询问教授是否对使用数组有任何限制。遵循分配规则并获得好成绩,但要知道没有理智的程序员会在这里使用
if/else if。如果不允许使用数组,请询问switch/case。if/else if应该是最后的手段。 -
@RetiredNinja 一个合理但无聊的故事。我也接受“因为正确使用
srand/rand是未来的课程。”我很可能会称赞“因为现在是 2018 年,srand/rand很愚蠢,所以我将在接下来的几周内教<random>库。” -
@McMissile
srand(time(0));不会“随机播种函数”。多次调用srand会使事情变得更糟:很可能整个for循环将在几分之一秒内运行,所以如果你在每次rand()调用之间调用srand(time(0)),你可以得到相同的结果rand()全部 1000 次!