c++ - C++如何输出两组不同的随机数?

标签 c++ function random

到目前为止,这是我的代码:

#include <iostream>
#include <time.h>
#include <stdio.h>      
#include <stdlib.h>  
using namespace std;

int DealerRoll(int dealerRoll)
{
        srand (time(NULL));
    for (int dealerCount = 1; dealerCount <= 3; dealerCount++)
    {
    dealerRoll = rand()% 6+1;
    cout << dealerRoll << " ";
    }
    return dealerRoll;
}
int PlayerRoll(int playerRoll)
{

        srand (time(NULL));
    for (int playerCount = 1; playerCount <= 3; playerCount++)
    {
    playerRoll = rand()% 6+1;
    cout << playerRoll << " ";
    }
    return playerRoll;
}

int main()
{
    int dealerRoll;
    int playerRoll;

    cout << "Dealer's Roll: " << endl;
    DealerRoll(dealerRoll);
    cout << endl << "Your Roll: " << endl;
    PlayerRoll(playerRoll);
system ("pause");
return 0;
}

我的问题是庄家和闲家的随机(骰子)掷骰总是相同的。例如,输出将是这样的:

Dealer's Roll: 
1 6 3 
Your Roll: 
1 6 3  

像这样如何让玩家的掷骰与庄家的掷骰不同?

Dealer's Roll: 
1 6 3 
Your Roll: 
4 2 5

最佳答案

这是因为你不断地重置你的种子。不直观地,这需要只做一次,否则你每次都会返回相同的看似随机的数字。 (实际上确实有特定的用例,这就是您想要做的)要只执行一次,请在执行的顶部包含此行一次,而不是在您的函数的每个连续循环中。

srand (time(NULL));

引用这个关于该主题的其他更深入的答案。

srand() — why call it only once?

关于c++ - C++如何输出两组不同的随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43268865/

相关文章:

c++ - 关于从派生类在基类中实现的C++调用虚函数的问题

c++ - 像普通方法一样调用构造函数和析构函数的注意事项和风险?

c++ - 共享指针不增加 use_count

甲骨文 : how to ensure that a function in the where clause will be called only after all the remaining where clauses have filtered the result?

c - 为什么 RAND_MAX 在 linux 和 windows 的同一台机器上不同?

c++ - Xcode 生成的存档文件缺少 dylib

c - 初级内存分配

c++ - main() 的链接是实现定义的是什么意思?

java - HashMap if containsValue 无限循环问题

python - MySQL插入时如何生成唯一的随机数?