我的代码有问题!当我使用{“T,Q,J,K,A”}的组合输入5张牌时,它不会计算得分,而是跳到“你想再玩一次”。 我相信它的逻辑错误但似乎无法找到它!任何人都可以帮我解决这个挑战吗?
#include <iostream>
using namespace std;
int main()
{
int cardnum, total=0, aceCount=0, i;
char face, ans;
do
{
total = 0;
cout << "How many Cards Do you have in your hands? (Between 2 and 5):\n";
cin >> cardnum;
if(cardnum <2 || cardnum > 5)
{
cout << "Not a Valid number of cards!\n";
}
cout << "Please enter Your Card Values.(2-9 or T, J,Q,K, A): \n";
for(i=0; i<cardnum; i++)
{
cin >> face;
switch (face)
{
case '2' :
total+=2;
break;
case '3' :
total+=3;
break;
case '4' :
total+=4;
break;
case '5' :
total+=5;
break;
case '6' :
total+=6;
break;
case '7' :
total+=7;
break;
case '8' :
total+=8;
break;
case '9' :
total+=9;
break;
case 't' :
case 'j' :
case 'q' :
case 'k' :
case 'T' :
case 'J' :
case 'Q' :
case 'K' :
total+=10;
break;
case 'A' :
case 'a' :
total+=11;
aceCount++;
}
}
if(total <=21)
{
cout << "Your Total Score is: " << total<<endl;
}
else if(aceCount > 0 && total > 21)
{
do
{
total-=10;
aceCount--;
}while (aceCount > 0 && total >21);
if(total <=21)
{
cout << "Your Total Score is: " << total<<endl;
}
}
else if(total > 21)
{
cout << "Your Total Score is: " << total<< " Which Means You Busted!\n";
}
cout << "Do You Wish to Calculate Your Score Again? (Type y OR Y).\n";
cin >> ans;
}while(ans == 'y' || ans=='Y');
cout << "GOOD BYE! Play NEXT TIME!\n";
system("PAUSE");
return 0;
}
答案 0 :(得分:0)
if(total <=21)
{
cout << "Your Total Score is: " << total<<endl;
}
你在两条线上都有这个,所以你的其他所需条件都没有得到满足。 只需将其第二次迭代更改为:
if(total > 21)
{
cout << "Your Total Score is: " << total<<endl;
}
答案 1 :(得分:0)
修复缩进,使问题更加明显。
当您在第一个else块中输入ace处理代码时,将不会执行第三个else块。所以只有在&lt; = 21时才打印得分。你应该在处理完Aces后进行打印,这两个块应该是相互独立的。
未经测试,但代码应如下所示:
if(aceCount > 0 && total > 21)
{
do
{
total-=10;
aceCount--;
}while (aceCount > 0 && total >21);
}
if(total <=21)
cout << "Your Total Score is: " << total<<endl;
}
else if(total > 21)
{
cout << "Your Total Score is: " << total<< " Which Means You Busted!\n";
}