2012-04-04 96 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; 
}