我尝试编写一个 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");
}
最佳答案
你有一个差一错误:当你到达最后一个元素并且 i
比 size
小一个时,arrat[i+1]
正在引用数组末尾之后的元素。
由于将 check
更改为 false
是一种“单行道”,您可以通过在检测到后立即返回 false
来简化您的函数错误的订单;到达函数末尾时返回 true
。
您还可以将升序/降序检查移到循环内以使代码更加统一:
for (int i = 0; i < size-1 ; i++) {
if (des && (array[i]<array[i + 1])
|| !des && (array[i]>array[i + 1])) {
return false;
}
}
return true;
关于c++:检查数组的顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29492788/