我正在创建一个程序,你需要使用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;
}
答案 0 :(得分:17)
您需要实际调用该函数:
if (inOrder(first, second, third))
此
if (inOrder)
总是计算为true,因为它确实检查了函数指针是否为非空。
答案 1 :(得分:9)
您必须存储函数的返回值,并测试它 - 或者直接测试函数。所以:
bool result = inOrder(first, second, third);
if (result)
{
(...)
或:
if (inOrder(first, second, third)
{
(...)
if(inOrder)
始终评估为true的原因是它检查inOrder()
函数的地址,该函数非零。
答案 2 :(得分:2)
可能是你的意思
if (inOrder(first, second, third))
而不是
inOrder(first, second, third);
if (inOrder)
当你说if (inOrder)
你实际上没有调用函数并检查结果时,而是使用变量inOrder作为条件,它只是指向函数入口点的指针,该函数总是计算为真。
答案 3 :(得分:2)
试试这个:
bool b = inOrder(first, second, third);
if(b){.....}
您没有从inOrder
函数
答案 4 :(得分:1)
始终为true
,因为您将函数的地址传递给if条件。由于该函数永远不会在地址0,因此条件始终为真。您需要存储函数的返回值:
bool ordered = inOrder(first, second, third);
或在if:
中调用该函数if (inOrder(first, second, third))
答案 5 :(得分: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;
}