【发布时间】:2023-03-22 00:16:01
【问题描述】:
代码的作用是询问用户他想要哪张卡,并根据选择的卡打印出一份声明。
如果输入了 1,2 和 3 以外的数字,我的目标是循环回到卡片选择功能。
还有一个 for 循环允许这个过程进行多次。
什么是最好的方法,我该怎么做?
int CardSelect() {
cout << "Enter 1 for hearts" << endl;
cout << " " << endl;
cout << "Enter 2 for diamonds" << endl;
cout << " " << endl;
cout << "Enter 3 for joker" << endl;
return 0;
};
int main() {
for (int i = 1; i <= 5; i++) {
CardSelect();
int cardchoice;
cin >> cardchoice;
cardchoice = CardSelect();
if (cardchoice == 1) {
cout << "You got hearts" << endl;
loop = false;
} else if (cardchoice == 2) {
cout << "You got diamonds" << endl;
loop = false;
} else if (cardchoice == 3) {
cout << "You got joker" << endl;
loop = false;
} else {
cout << "Invalid choice" << endl;
cout << "Please ensure you type in the right numbers" << endl;
}
}
}
【问题讨论】:
-
CardSelect()总是返回零,因此它不会像您尝试的那样做。 -
CardSelect()直接擦除存储在cardchoice中的使用输入 -
有什么建议吗?
-
如果您想显示这些消息,只需使用 void 类型函数。如果您只想显示函数中的某些内容,则返回任何内容都没有意义。
-
@coder 在你的 main 中这些
loop = false语句背后的逻辑是什么?首先没有名为循环的布尔/布尔变量,其次如果你想在输入后中断为什么要使用循环?
标签: c++ if-statement while-loop