【发布时间】:2020-02-26 21:48:35
【问题描述】:
我正在尝试创建一个程序,该程序将从一副 52 张常规扑克牌中抽出一张牌。
花色:红心、黑桃、钻石、梅花。
排名:A,2,3,4,5,6,7,8,9,10,J,Q,K。
这应该是输出:
Let's pull a card!
This time we got AH
Wanna pull a card again?
y
This time we got 3J
Wanna pull a card again?
n
我的输出是:
Let's pull a card!
DKThis time we got 00
Wanna pull a card again?
n
这是我的代码:
#include <iostream>
#include <ctime>
using namespace std;
// Function Declaration
int rankCard(), suitCard();
int main()
{
srand(time(0));
char answer;
cout << "Let's pull a card!" << endl;
do {
cout << "This time we got " << rankCard() << suitCard() << endl;
cout << "Wanna pull a card again?" << endl;
cin >> answer;
} while ((answer == 'y') || (answer == 'Y'));
return 0;
}
int rankCard() {
int rank = (rand() % 13) + 1;
switch (rank) {
case 1: cout << "A";
break;
case 10: cout << "T";
break;
case 11: cout << "J";
break;
case 12: cout << "Q";
break;
case 13: cout << "K";
break;
default: cout << rank;
break;
}
return 0;
}
int suitCard() {
int suit = (rand() % 4) + 1;
switch (suit) {
case 1: cout << "H";
break;
case 2: cout << "D";
break;
case 3: cout << "C";
break;
case 4: cout << "S";
break;
}
return 0;
}
我无法弄清楚为什么拉出的牌(DK)在那个位置,为什么我也得到 00。我做错了什么?谢谢
【问题讨论】:
-
欢迎来到 Stack Overflow!听起来您可能需要学习如何使用调试器来逐步执行代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。进一步阅读:How to debug small programs 和 Debugging Guide
-
想想每个函数的返回类型,比如
int suitCard()——应该是char suitCard()吗?在这种情况下,您将如何更改函数中的cout和return语句? -
cout << "This time we got " << rankCard() << suitCard() << endl;因为 rankCard 和 suitCard 都返回 0,所以它们打印 0。 -
注意:输出“This time we got 3J”似乎不正确,因为“J”不是西装。