【问题标题】:how do I use else and if statements [closed]我如何使用 else 和 if 语句 [关闭]
【发布时间】:2019-08-20 01:18:35
【问题描述】:

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

我尝试了两个 if 语句 else if 和 else

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

【问题讨论】:

  • 尝试在左侧写条件if(true = hit)
  • cin &gt;&gt; hit, stand; 不会像您认为的那样做。您正在尝试输入单个字符串,对吗?然后你想在单独的 if 语句中将它与字符串“hit”和字符串“stand”进行比较。
  • 我没有看到任何“其他”陈述。您还必须使用 == 进行比较。
  • 看来你可以使用a couple of good books阅读。

标签: c++ if-statement blackjack


【解决方案1】:

sn-p:

bool hit;
bool stand;
cin >> hit, stand; 

不会根据您输入的内容神奇地设置其中一个布尔值。您的 cin 语句将尝试从用户那里获取两个单独的布尔值。

您可能想要做的是获得一个 string 然后对其采取行动,例如:

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,然后将其用作条件。因此它永远是正确的。

另请参阅 here,了解针对 true 和/或 false 显式检查布尔值的荒谬之处。

【讨论】:

    【解决方案2】:

    打或站是一个选择,因此您需要一个布尔变量。

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

    【讨论】:

    • 既然 OP 已经声明他们想要输入“hit”和/或“stand”,布尔值可能是错误的选择。
    • 打或站是唯一的选择。当然,您会做出多个这样的选择,这显然需要一个循环。我认为 OP 通常会感到困惑,需要放慢速度,或者先尝试一些更简单的东西。
    猜你喜欢
    • 1970-01-01
    • 2017-09-05
    • 2016-10-15
    • 2018-03-29
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    • 2014-08-12
    • 1970-01-01
    相关资源
    最近更新 更多