生成两个不同的随机数

时间:2017-04-16 13:37:05

标签: c++

我要创建一个简单的" Craps"使用C ++的游戏

在"掷骰子",当玩家掷骰子不是立即赢或输的时候,他们需要再扔掉它

但是当我需要再次掷骰子时我无法改变骰子数量

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

using namespace std;

void again(int first) {
    srand(time(NULL));
    int dice11, dice22, total2;
    do {
        dice11 = (rand() % 6 + 1);
        dice22 = (rand() % 6 + 1);
        total2 = dice11 + dice22;
        cout << "Player throw " << total2 << endl;
        if (total2 == first)
            cout << "Player Win" << endl;
        if (total2 == 7)
            cout << "Player Lose" << endl;
    } while (total2 != first);

}



int main() {
    srand(time(NULL));
    int dice1, dice2,total;
        dice1 = (rand() % 6 + 1);
        dice2 = (rand() % 6 + 1);
        total = dice1 + dice2;

        if (total == 7 || total == 11)
            cout << "Player throw " << total << " Player Win" << endl;
        else
            if (total == 2 || total == 8 || total == 12)
                cout << "Player throw " << total << " Player Lose" << endl;
            else
            {   
                cout << "Player throw " << total << endl;
                again(total);
            }


    system("pause");
    return 0;
}

在程序中,我已经创建了一个使用&#34; srand()&#34;的函数。再次,但它仍然无法正常工作

2 个答案:

答案 0 :(得分:2)

您对srand的第二次调用(在函数again中)可能正在将随机数生成器初始化为与前一次调用相同的种子。 time()计算秒数(主要是C++ reference)。不要重新初始化随机数生成器 - 除非您想重新创建以前生成的随机数序列。

答案 1 :(得分:1)

  

在程序中,我已经创建了一个使用&#34; srand()&#34;的函数。再次,但它仍然无法正常工作

那是因为你再次使用srand()

在你的课程开始时只做一次。

the cppreference documentation中对此进行了解释。你在没有文档的情况下编程吗?