3

我正在制作一个程序,您需要使用 bool 函数来确定三个数字在用户输入时是否按升序排列。但是,bool 函数的计算结果始终为真。我错过了什么?这是我的代码:

#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;
}
4

6 回答 6

18

您需要实际调用该函数:

if (inOrder(first, second, third))

if (inOrder)

总是评估为真,因为它确实检查函数指针是否为非空。

于 2012-04-04T15:28:04.920 回答
9

您必须存储函数的返回值,并对其进行测试——或者直接测试函数。所以:

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

if (result)
{
(...)

或者:

if (inOrder(first, second, third)
{
(...)

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

于 2012-04-04T15:27:38.100 回答
2

可能是你的意思

if (inOrder(first, second, third))

代替

inOrder(first, second, third);

if (inOrder)

当你说if (inOrder)你实际上没有调用函数并检查结果时,而是使用变量 inOrder 作为条件,它只不过是指向函数入口点的指针,它总是评估为真。

于 2012-04-04T15:28:30.757 回答
2

试试这个:

bool b = inOrder(first, second, third);
if(b){.....}

你没有从inOrder函数中获取结果

于 2012-04-04T15:35:13.113 回答
1

这总是true因为您将函数的地址传递给您的 if 条件。由于函数永远不会位于地址 0,因此条件始终为真。您需要存储函数的返回值:

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

或在 if 中调用函数:

if (inOrder(first, second, third))
于 2012-04-04T15:29:45.450 回答
0

这是工作副本。您需要存储函数调用中的 o/p。

#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;
    bool isordered;
    isordered = inOrder(first, second, third);

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

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

    return 0;
}
于 2012-04-04T15:37:04.843 回答