我是一个初学者,我并没有完全理解我使用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;
int card1 = rand() % 10 + 1;
int newCard = rand() % 10 +1;
你正确地处理了前两张牌(a)但是,之后的任何时候你都没有真正处理后续牌。相反,你检查的每张所谓的新牌都只是第二张牌的副本。
你需要做的是在玩家正在击球的情况下实际生成一张新牌。
这就像在循环中插入一行一样简单:
while(deal == 'y' || deal == 'Y')
{
newCard = rand() % 10 +1; // <<<--- this one.
cout << "\n New Card = " << newCard;
:
}
(a)对于二十一点来说不太正确,因为有十张超值卡而不是普通牌(10 / J / Q / K都有十张值)。
更好的方法是使用类似的东西:
newCard = rand() % 13 + 1;
if (newCard > 10) newCard = 10;
你的问题
你只能像这样在开始时调用rand()
一次
int card1 = rand() % 10 + 1;
int newCard = rand() % 10 +1;
但是,每次需要新值时,都需要像这样分配新卡
newCard = rand() % 10 +1;
再次使用之前。您必须反复调用它来获取新值。
一个提示
仅仅因为它尚未被提及,here是一个很好的谈论为什么你不应该使用std::rand()
。虽然其他答案也会产生随机数,但它们的分布可能会关闭。 C++
提供了一种获取随机数的更好方法,我建议你尽快习惯它。
std::random_device rd; //Will be used to obtain a seed for the random number engine
std::mt19937 gen(rd()); //Standard mersenne_twister_engine seeded with rd()
std::uniform_int_distribution<> dis(1, 10);
int newCard = dis(mt);
您需要以下标题
#include <random>
#include <iostream>
如果你需要更好的随机性,你可以使用random_device
而不是mt19937生成器。
所以我建议从一开始就这样做,并从你的代码中删除rand()
。