c++ - 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;
}
}
解决方案
如果你想生成一个随机数,你需要调用rand()
.
所以在这里:
int newCard = rand() % 10 +1;
我掷了一个 10 面的骰子,结果是 5,所以我在一张标有 newCard 的纸上写了 5。
现在,每次我看我那张标有 newCard 的纸时,它仍然会显示 5。我每次看它时都不会改变。
如果您想再次滚动,您需要再次滚动并记下新数字,再次运行:
newCard = rand() % 10 +1;
推荐阅读
- python - 为什么 python 中的 sqlite delete table 比 sqlite3 shell 慢数千倍?
- heremaps - HERE Maps JS 在收到 HTTP 204 NO CONTENT 时显示水彩
- python - Python 请求:如何获取空白隐藏输入的值
- gnuradio - GNURadio 无法找到 USRP n3xx 但可以从主机 ping 设备,以及使用 uhd_find_devices、uhd_usrp_prob 找到设备
- reactjs - 无法启动应用程序/本机模块无法打开 Null
- excel - 在 msgbox 中显示唯一值
- reactjs - Axios 从 dhango-rest-framework api 中一无所获
- apache-spark - Spark 配置未更新
- mysql - 按最高成绩排序学生,然后为每个学生排序
- python - 在 admin 中显示 prepopulated_fields 的外键属性