gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 04:33:42 24 4
gpt4 key购买 nike

我是初学者,我不完全理解我在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com