2012-04-04 279 views
3

我正在製作一個程序,您需要使用布爾函數來查明三個數字是否在用戶輸入時按升序排列。但是,布爾函數總是評估爲真。我錯過了什麼?這裏是我的代碼:布爾總是評估爲真

#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; 
} 
+0

爲什麼你調用if之外的函數並且你不把結果賦值給一個值? – kappa 2012-04-04 15:28:28

+7

'if(something){return true;} else {return false;}'可以(並且應該)總是重寫爲'return something;'。 – ipc 2012-04-04 15:29:00

+0

+1生產一個完整的測試用例。 http://sscce.org/。 – 2012-04-04 15:54:26

回答

17

您需要實際調用該函數:

if (inOrder(first, second, third)) 

if (inOrder) 

結果始終爲true,因爲它確實檢查,函數指針是否非空。

+0

非常好!非常感謝。 – quasipsychotic 2012-04-04 15:34:17

9

你必須存儲函數的返回值,並測試 - 或者只是直接測試功能。所以:

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

if (result) 
{ 
(...) 

或:

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

而對於if(inOrder)的原因一直在評估爲true,它會檢查inOrder()功能,這是非零的地址。

2

可能是你的意思

if (inOrder(first, second, third)) 

,而不是

inOrder(first, second, third); 

if (inOrder) 

當你說if (inOrder)你實際上不調用該函數並檢查結果,而不是你所使用的變量序爲條件這只不過是指向函數的入口點的指針,它總是評估爲真。

1

它總是true,因爲您將函數的地址傳遞給if條件。由於該函數永遠不會位於地址0,因此該條件始終爲真。您需要可以存儲函數的返回值:

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

或調用函數中,如果:

if (inOrder(first, second, third)) 
2

試試這個:

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

你不採取結果inOrder功能

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