【问题标题】:While Loop, and gen rand() [closed]While 循环和 gen rand() [关闭]
【发布时间】:2013-02-27 21:04:57
【问题描述】:

所以我基本上是在创建一个二十一点游戏,我被困在我必须询问用户是否想要另一张牌(Take a HIT)的地方,我决定做一个 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;
}

【问题讨论】:

  • 这是一些设置了约束的功课,还是你自己学习?
  • @hyde 这是功课
  • @Johnsyweb 不,这是关于受到打击,而不是生成用户第二张卡片
  • 从洗好的牌组中随机抽取第三张、第四张、……五十一张牌……都是一样的。

标签: c++ loops random while-loop


【解决方案1】:

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

【讨论】:

  • 不幸的是,我只能做我们在课堂上学到的东西,所以几乎是 if 语句和循环
  • @MichaelRamos 那么你应该在问题中清楚地说明你的要求,因为它们是非常人为的。
【解决方案2】:

看起来像是一个你应该使用数组的练习。我无法为您编写程序,但请阅读数组 - 它们是解决方案的重要组成部分。您可以创建一个由 52 个布尔变量组成的数组,指示哪些卡片已被选中。你应该设计一个算法来检查一张牌是否被选中,当我们得到一张随机挑选的牌时,继续挑选一张新牌。

【讨论】:

  • 我们没有覆盖数组,所以我不能使用它们
猜你喜欢
  • 2015-08-02
  • 2023-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-14
  • 2016-03-25
  • 2014-03-22
  • 1970-01-01
相关资源
最近更新 更多