【发布时间】:2015-04-07 13:26:13
【问题描述】:
我尝试编写一个 bool 函数,接受一个数组和一个 bool dec。如果 dec 为真,则该函数将检查它是否下降,如果下降则返回 true。如果 dec 为 false,则函数将在升序时返回 true。
如果我用这个函数测试数组,它应该返回 false,但它返回 true,我不知道为什么。 任何人都可以帮忙吗?谢谢。
#include <iostream>
#include <cstring>
#include <cmath>
#include <iomanip>
using namespace std;
bool isSorted(int array[], int size, bool dec) //false decending
{
bool check = true;
if (dec == false)
for (int i = 0; i<size; i++)
if (array[i]>array[i + 1])
{
check = false;
cout << "false";
}
else
for (int i = 0; i<size; i++)
if (array[i]<array[i + 1])
check = false;
return check;
}
int main() {
int n;
bool asc=true;
bool result;
int arr[] = { 1, 2, 4, 3, 0 };
n = 5;
result = isSorted(arr, n, asc);
cout << result;
system("pause");
}
【问题讨论】:
-
对于真正的代码,这将是对
std::is_sorted的调用。 -
请注意使用此索引保持在界限内:
array[i + 1]