我如何使用else和if语句[关闭]

问题描述 投票:-3回答:2

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

我已经尝试了两个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

c++ if-statement blackjack
2个回答
2
投票

片段:

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

另请参阅here,了解明确检查针对true和/或false的布尔值的荒谬性。


-1
投票

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

bool hit;
cin >> hit;

hit是一个布尔变量,所以它已经为假,你不需要将它与true(或false)进行比较。所以只是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 ++语法和规则的基础知识时,您需要编写少量代码。即使在这个简短的程序中,您也会遇到多个错误,并且在发生这种情况时很难弄清楚出现了什么问题。在这个阶段,你应该一次写一行代码。在编写下一行之前测试以确保它有效。

© www.soinside.com 2019 - 2024. All rights reserved.