3

ユーザーが入力したときに3つの数値が昇順であるかどうかを調べるために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;
}
4

6 に答える 6

18

実際に関数を呼び出す必要があります。

if (inOrder(first, second, third))

これ

if (inOrder)

関数ポインターが null でないかどうかを実際にチェックするため、常に true と評価されます。

于 2012-04-04T15:28:04.920 に答える
9

関数の戻り値を保存してテストするか、関数を直接テストする必要があります。そう:

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

if (result)
{
(...)

また:

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

if(inOrder)また、常に true と評価される理由はinOrder()、ゼロ以外の関数のアドレスをチェックするためです。

于 2012-04-04T15:27:38.100 に答える
2

これを試して:

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

あなたはinOrder機能から結果を得ていません

于 2012-04-04T15:35:13.113 に答える
2

あなたが意味するかもしれません

if (inOrder(first, second, third))

それ以外の

inOrder(first, second, third);

if (inOrder)

実際に関数を呼び出して結果をチェックしていないと言うif (inOrder)ときは、代わりに変数 inOrder を条件として使用しています。これは、常に true と評価される関数のエントリ ポイントへのポインタにすぎません。

于 2012-04-04T15:28:30.757 に答える
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 に答える