C++使用ctime作为随机数生成器但仍然得到相同的数字

标签 c++ srand ctime

我是初学者,我不完全理解我在使用 ctime 和分配随机数的变量时做错了什么。我的 newCard 变量每次调用它时都会返回相同的值。对于任何反馈,我们都表示感谢!

这个程序是循环审查,不能包含用户定义的函数

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

int main()
{
    srand(static_cast<unsigned>(time(0)));

    int total = 0;
    int card1 = rand() % 10 + 1;
    int newCard = rand() % 10 +1;
    char deal, replay;

    do
    {   
         cout << " First Cards: " << card1 << ", " << newCard;
         total = card1 + newCard;
         cout << "\n Total: " << total;
         cout << "\n Do you want another card? (Y/N) ";
         cin >> deal;

         while(deal == 'y' || deal == 'Y')
         {
             cout << "\n New Card = " << newCard;
             total += newCard;
             cout << "\n Total: " << total;

            if(total == 21)
            {
                cout << "\n Congratulations!! BLACKJACK! ";
                cout << "\n Would you like to play again? (Y/N):";
                cin >> replay;
                break;
            }
            else if(total > 21)
            {
                cout << "\n BUST ";
                cout << "\n Would you like to play again? (Y/N):";
                cin >> replay;
                break;
            }

            cout << "\n Would you like another card? (Y/N): ";
            cin >> deal;
         }

         while (deal == 'n' || deal == 'N')
         {
             cout << "\n Would you like to play again? (Y/N): ";
             cin >> replay;
         }
    }
    while(replay == 'y' || replay == 'Y');

    while (replay =='n' || replay == 'N')
    {
        cout << "\n Exiting BlackJack \n\n";
        return 0;
    }
}

最佳答案

如果你想生成一个随机数,你需要调用rand()

所以在这里:

int newCard = rand() % 10 +1;

我掷一个 10 面的骰子,结果是 5,所以我在一张标有 newCard 的纸上写下 5。

现在,每次我看我那张标有 newCard 的纸时,它仍然会显示 5。每次我看它都不会改变。

如果你想再次滚动,你需要再次滚动并记下新数字,再次运行:

newCard = rand() % 10 +1;

关于C++使用ctime作为随机数生成器但仍然得到相同的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52142206/

相关文章:

c++ - 堆上整数 vector 和释放内存

c++ - Emacs、Cedet 和语义

c - 仅循环迭代一半元素

c - 我如何在 C 中打印日期?

c++ - CUDA:最小化大数据类型的银行冲突

c++ - 从内存地址到源代码行

c - 将 srand() 放在头文件中是个好主意吗?

c - srand() — 为什么只调用一次?

c++ - 使用 time() 函数计算执行时间

c++ - 我所在地区的时间相关信息是否有上限?