首页 > 解决方案 > C++ 使用 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;
    }
}

标签: c++srandctime

解决方案


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

所以在这里:

int newCard = rand() % 10 +1;

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

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

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

newCard = rand() % 10 +1;

推荐阅读