【问题标题】:If/else if not executing even though it appears conditions are met inside of a while loopIf/else if not execution 即使它出现在 while 循环内满足条件
【发布时间】:2013-03-14 03:20:47
【问题描述】:

和标题说的差不多。我到了这个彩票号码分配的最后一点,我不确定为什么在调试时没有显示第二组 if/else if 语句。我知道 if/else 语句是互斥的 - 但不应该一个 if 和另一个 if 都测试吗? 这是代码。

count=0;
while(count<5)
{
    if(lottery[count] == user[count])
    {
        lotto = lottery[count];
        cout<<"So, you matched numbers with "<<lotto <<".\n";
        tally++;
    }
        if(tally==5 && count == 5)
        {
            cout<<"Congratulations, you're the grand prize winner!";
        }
        else if(tally < 5 && count == 5)
        {
            cout<<"A total of "<<tally<<" of your lottery picks matched.";
        }
        else if(tally == 0 && count == 5)
        {
            cout<<"Caution. The following comment is an inside joke. Read at your own risk.";
            cout<<"Bet you feel like a total loser huh? Nothing matched.";
        }

    count++;
}

我知道为了简单起见,我可能应该用 for 循环替换 while 循环,但我更喜欢 while。

【问题讨论】:

  • 你有没有在调试器中逐行检查代码?

标签: c++ while-loop if-statement


【解决方案1】:
if 块被执行时,

count永远成为5

一旦变为5,条件失败,循环停止。

【讨论】:

    【解决方案2】:

    count 永远不会等于 5 在 while 循环中的 if-else 条件需要它的点。如果您在if-else 之前之前增加了count,那么就有可能满足其中一个条件(取决于tally 的值)。

    【讨论】:

    • 该死的一个……也请阅读本章中的内容。哦。谢谢!
    • 这不是真的。 count 在 while 循环之后将等于 5。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-08-15
    • 2022-01-20
    • 2019-08-09
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多