if语句下只有一个语句正在运行

only one statement under if statement being run

本文关键字:语句 运行 if 有一个      更新时间:2023-10-16

我用C++编写了一个程序,要求输入任何整数。程序仅在两次迭代后就崩溃了。代码如下:

#include<iostream>
int main()
{   
    int user_choice;
    std::cout <<"Please enter any number other than five: ";
    std::cin >> user_choice;
    while(user_choice != 5)
    {
        std::cout <<"Please enter any number other than five: ";
        std::cin >> user_choice;
        if(user_choice == 5)
            std::cout << "Program Crash";
            break;
    }
    std::cout << "I told you not to enter 5!";
    return 0;
}

然后我试着这样做:

if(user_choice == 5)
    std::cout << "Program Crash";
    //std::cout << "Shutting Down";

这起到了作用。为什么注释掉第二行,会导致程序运行良好?

此代码:

if (counter == 10)
    std::cout << "Wow you still have not entered 5. You win!";
    user_choice = right_answer;

相当于:

if (counter == 10)
{
    std::cout << "Wow you still have not entered 5. You win!";
}
user_choice = right_answer;

您的问题变得显而易见,user_choice = right_answer不是仅在counter == 10时执行的。因此,将其移动到if () { ... }块内:

if (counter == 10)
{
    std::cout << "Wow you still have not entered 5. You win!";
    user_choice = right_answer;
}

C++不尊重缩进;所以当你写:

if (counter == 10)
    std::cout << "Wow you still have not entered 5. You win!";
    user_choice = right_answer; 

编译器看到:

if (counter == 10)
    std::cout << "Wow you still have not entered 5. You win!";
user_choice = right_answer; 

要将两个语句都放在if下,需要大括号:

if (counter == 10) {
    std::cout << "Wow you still have not entered 5. You win!";
    user_choice = right_answer; 
}