【问题标题】:How to output two different sets of random numbers in C++?如何在 C++ 中输出两组不同的随机数?
【发布时间】:2017-09-02 07:00:19
【问题描述】:

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

#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

【问题讨论】:

    标签: c++ function random


    【解决方案1】:

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

    srand (time(NULL));
    

    参考关于该主题的其他更深入的答案。

    srand() — why call it only once?

    【讨论】:

    • 不是这个问题的原因,因为他用时间重新播种(NULL)
    • Nathan,至少在 C++ 中是这样完成的。注释掉“srand (time(NULL));”从他的函数中提取行并在 main 顶部添加它的一个实例使代码对我来说完美无缺。
    • 还有一个错误,但我认为它是及时的(NULL),这可能是它没有正确重新播种的原因
    • 该睡觉了。祝你好运!
    • @NathanielJohnson 问题在于time(NULL) 只返回精确到每一 的时间,因此如果您每秒多次调用time(NULL),您将得到相同的数字。显然调用这两个函数之间的时间可能是大约百万分之一秒,所以......
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 2018-01-02
    • 1970-01-01
    • 1970-01-01
    • 2012-08-30
    • 2022-01-04
    相关资源
    最近更新 更多