如何使用 else 和 if 语句
how do I use else and if statements
当我运行代码时,我的两个选项都出现了
我已经尝试了两个if语句,否则
cout << "would you like to hit or stand?" << endl; //asking if you would ike to hit or stand
bool hit; //the hjitting opption
bool stand; // the stand / hit option
cin >> hit, stand; // the avaiabillity for hitting or standing (player input)
if ( hit = true) // if you hit
{
for (n = 1; n <= 1; n++) //loop for how many cards are you have
{
num = rand() % 13; //get random number
cout << num << "t"; //outputting the number
}
}
{
cout << "you stand n"; // saying you stand
我希望代码在你说命中时输出数字,当你说站立时说你站立,但它要么只把命中放在支架上,要么两者兼而有之enter code here
代码片段:
bool hit;
bool stand;
cin >> hit, stand;
不会根据您输入的内容神奇地设置其中一个布尔值。您的cin
语句将尝试从用户那里获取两个单独的布尔值。
您可能想做的是获取一个字符串,然后对其进行操作,例如:
std::string response;
std::cin >> response;
if (response == "hit") {
do_hitty_things();
} else if (response == "stand") {
do_standy_things();
} else {
get_quizzical_look_from_dealer();
}
此外(虽然如果你接受我的建议无关紧要(,表达hit = true
是一个作业而不是比较。比较将使用==
.if (hit = true)
的结果是首先将hit
设置为true
,然后将其用作条件。因此,它将永远是真的。
另请参阅此处,了解明确检查布尔值与true
和/或false
的荒谬性。
击球或站立是一种选择,因此您需要一个布尔变量。
bool hit;
cin >> hit;
hit
是一个布尔变量,所以它已经是假的,你不需要把它与真(或假(进行比较。所以只要if (hit)
就可以了。如果要将其与true
进行比较,那么它==
不=
,所以if (hit == true)
也可以。
最后,由于您的选择会产生两个备选方案,因此您需要一个if ... else ...
语句。
if (hit)
{
for (n = 1; n <= 1; n++) //loop for how many cards are you have
{
num = rand() % 13; //get random number
cout << num << "t"; //outputting the number
}
}
else
{
cout << "you stand n"; // saying you stand
}
当您仍在学习C++语法和规则的基础知识时,您需要编写少量代码。即使在这个简短的程序中,您也存在多个错误,并且很难弄清楚发生这种情况时出了什么问题。在这个阶段,你应该一次写一行代码。在编写下一行之前对其进行测试以确保其正常工作。
相关文章:
- Insert函数不适用于2 if语句C++
- If语句未被求值C++
- C++嵌套if语句,基本货币交换
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- If语句在c++中被忽略
- 比较if语句中的数组值和int值
- 以在Qt中的IF语句中设置时间延迟
- Craps游戏问题,忽略if语句
- c++:定义if语句中的模板
- C++嵌套的 If 语句中,它无法按预期工作
- 如果条件不相关,我应该更喜欢两个 if 语句而不是 if-else 语句吗?
- 需要有关此 if 语句的帮助
- 转换器练习:跳过 if 语句和 if 语句
- 避免在 C++ 中的 if 语句中递增
- 如果仍然不满足要求,如何使 if 语句重复?
- do while 循环中的 if 语句以 yes 或 no 结尾
- 为什么在此C++代码中触发此 if 语句?
- 如何基于平台在制作文件中制作if语句?
- 在 if 语句中使用 GetKeyState 时,它会跳过条件
- C++ If 语句,从其他语句重复