2

如果我用 注释掉该行srand,程序将运行,但没有种子,因此每次的值都是相同的。作业要求我使用randsrandtime使骰子函数完全随机。

#include <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>

using namespace std;

int rollDice();
// function declaration that simulates the rolling of dice

int main() {

    int roll1 = rollDice();

    int roll2 = rollDice();

    // define, initialize, and combine dice roll total

    int total;

    total = 0;

    total = roll1 + roll2;

    * this is where a bunch of stuff is output to the screen from the dice rolls, using total as well as some other stuff that is being calculated, i left it out for simplicity*

}

// function to simulate a random dice roll

int rollDice() {

    int r;

    srand (time(NULL));

    r = (rand() % 6) + 1;

    return r;

}
4

1 回答 1

6

放入srandmain并调用一次。您必须使用一次种子才能从随机序列中获取所有结果。

在这里,您每次掷骰子时都重新开始序列。

请参阅文档srand()

于 2013-09-10T21:15:43.640 回答