布尔总是评价为真

qua*_*tic 3 c++ boolean

我正在制作一个程序,你需要使用bool函数来确定当用户输入时三个数字是否按升序排列.但是,bool函数始终评估为true.我错过了什么?这是我的代码:

#include <iostream>
#include <string>

using namespace std;

bool inOrder(int first, int second, int third)
{
    if ((first <= second) && (second <= third))
    {
        return true;
    }

    else
    {
        return false;
    }
}

int main()
{
    int first, second, third;

    cout << "You will be prompted to enter three numbers." << endl;
    cout << "Please enter your first number: ";
    cin >> first;
    cout << "Please enter your second number: ";
    cin >> second;
    cout << "Please enter your third and final number: ";
    cin >> third;
    cout << endl;

    inOrder(first, second, third);

    if (inOrder)
    {
        cout << "Your numbers were in ascending order!" << endl;
    }

    else
    {
        cout << "Your numbers were not in ascdending order." << endl;
    }

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Hen*_*rik 17

你需要实际调用该函数:

if (inOrder(first, second, third))
Run Code Online (Sandbox Code Playgroud)

这个

if (inOrder)
Run Code Online (Sandbox Code Playgroud)

总是计算为true,因为它确实检查函数指针是否为非null.


son*_*ave 9

您必须存储函数的返回值,并测试 - 或直接测试函数.所以:

bool result = inOrder(first, second, third);

if (result)
{
(...)
Run Code Online (Sandbox Code Playgroud)

要么:

if (inOrder(first, second, third)
{
(...)
Run Code Online (Sandbox Code Playgroud)

if(inOrder)总是评估为true 的原因是它检查inOrder()函数的地址,该地址非零.