c++ - While 循环和 gen rand()

标签 c++ loops random while-loop

<分区>

所以我基本上是在创建一个 21 点游戏,我卡在了必须询问用户是否想要另一张牌的地方(试一试),我决定做一个 while 循环。我想弄清楚的一个问题是我如何才能做到这一点,以便为第一个 HIT 选择的随机数不能再次选择,我卡住了,因为我将该变量分配给“card3”

while (hit == 'yes' || hit == 'Yes' || hit =='Y' || hit == 'y')
{
//create new card, add onto total, ask again
card3 = rand() % 51 + 1;
while (card3 == card1 || deal1 == card2 || card3 == deal1){
  card3 = rand() % 52 + 1;
}
if (card3 == 1 || card3 == 2 || card3 == 3 || card3 == 4){
cout <<"|A|";
total = total + 11;}
else if (card3 == 5 || card3 == 6 || card3 == 7 || card3 == 8){
cout <<"|2|";
total = total + 2;}
else if (card3 == 9 || card3 == 10 || card3 == 11 || card3 == 12){
cout <<"|3|";
total = total + 3;}
else if (card3 == 13 || card3 == 14 || card3 == 15 || card3 == 16){
cout <<"|4|";
total = total + 4;}
else if (card3 == 17 || card3 == 18 || card3 == 19 || card3 == 20){
cout <<"|5|";
total = total + 5;}
else if (card3 == 21 || card3 == 22 || card3 == 23 || card3 == 24){
cout <<"|6|";
total = total + 6;}
else if (card3 == 25 || card3 == 26 || card3 == 27 || card3 == 28){
cout <<"|7|";
total = total + 7;}
else if (card3 == 29 || card3 == 30 || card3 == 31 || card3 == 32){
cout <<"|8|";
total = total + 8;}
else if (card3 == 33 || card3 == 34 || card3 == 35 || card3 == 36){
cout <<"|9|";
total = total + 9;}
else if (card3 == 37 || card3 == 38 || card3 == 39 || card3 == 40){
cout <<"|10|";
total = total + 10;}
else if (card3 == 41 || card3 == 42 || card3 == 43 || card3 == 44){
cout <<"|J|";
total = total + 10;}
else if (card3 == 45 || card3 == 46 || card3 == 47 || card3 == 48){
cout <<"|Q|";
total = total + 10;}
else if (card3 == 49 || card3== 50 || card3 == 51 || card3 == 52){
cout <<"|K|";
total = total + 10;}
cout << endl;
cout <<"Your total is: " << total << endl;
cout <<"Would you like another card? yes or no: " << endl;
cin >> hit; 
cout << endl;
}

最佳答案

您可以将所有卡片放入容器中,然后使用 std::random_shuffle好吧,洗牌。然后从容器背面一次弹出一张卡片。套牌完成后,重新开始。

关于c++ - While 循环和 gen rand(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15122391/

相关文章:

c++ - 如何在不删除字符的情况下将 SQLCHAR[200] 类型转换为 std::string?

javascript - 使用 .foreach 从一个数组中删除另一个数组

java - Android:循环从ArrayList中选择随机图像

R:从一系列类别中随机抽取偶数个观察值

math - 寻找线性同余系统等分布解的算法

c++ - 继承和覆盖 std::string 的函数?

c++ - 转换到 int vs floor

c++ - 使用C++确定三个数中最大的数

php - 如何在 PHP/MYSQL 中将两个 mysql 查询作为一个执行?

loops - Else If 是否为 FileExists()