如何使用 else 和 if 语句

how do I use else and if statements

本文关键字:if 语句 else 何使用      更新时间:2023-10-16

当我运行代码时,我的两个选项都出现了

我已经尝试了两个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++语法和规则的基础知识时,您需要编写少量代码。即使在这个简短的程序中,您也存在多个错误,并且很难弄清楚发生这种情况时出了什么问题。在这个阶段,你应该一次写一行代码。在编写下一行之前对其进行测试以确保其正常工作。