小于运算符在执行几次后无法正常工作

Ben*_*Ben -1 c++ if-statement boolean-operations

我是学习 C++ 的初学者。就在今天,我尝试学习布尔运算符和if-else语句。

这是代码:

int main(){
    //if-else statement
    int a, b;
    bool result = (a < b);
    
    std::cout << "input number 1 : ";
    std::cin >> a;
    std::cout << "input number 2 : ";
    std::cin >> b;
    std::cout << std::boolalpha << result <<std::endl;
    if(result == true){
        std::cout << a << " is less than " << b << std::endl;
    }
    if(!(result == true)){
        std::cout << a << " is NOT less than " << b << std::endl;
    }
    
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

以下是几次执行后的结果:

图像

最初的结果很好,但几次之后就出错了。

有谁知道这是什么原因?

raw*_*rex 7

您的错误是在为这些变量result 分配任何正确的值之前比较这两个变量并保存。换句话说,您比较未初始化的变量ab具有未定义值的变量。

首先,你要做:

bool result = (a < b);
Run Code Online (Sandbox Code Playgroud)

然后在获得值后:

std::cin >> a;
std::cin >> b;
Run Code Online (Sandbox Code Playgroud)

您应该执行以下操作:

// ...
int a, b;
std::cout << "input number 1 : ";
std::cin >> a;
std::cout << "input number 2 : ";
std::cin >> b;

bool result = a < b; // <-- move this down here!
// ...
Run Code Online (Sandbox Code Playgroud)