-4
我在C中有一个简单的函数来获取数组是否已排序,但我似乎每次都得到不同的值。有时候我会通过3次测试,有时候会有2次测试通过,我不确定问题出在哪里。C:每次运行程序都会有不同的值
int is_sorted(int a[], int n)
{
for(int i = 0; i < n; i++)
{
if(a[i] > a[i + 1])
{
return 0;
}
}
return 1;
}
int main()
{
int a[] = {2, 4, 9, 8, 12};
int b[] = {-5, -2, 0, 8, 11, 15};
int aa[] = {2, 18, 12, 9, 1, 2, 8, 11, 16, 3};
int c[] = {4, 6, 8, 10};
npassed = 0;
if(!is_sorted(a, 5))
{
npassed++;
}
if(is_sorted(b, 6))
{
npassed++;
}
if(!is_sorted(aa, 10))
{
npassed++;
}
if(is_sorted(c, 5))
{
npassed++;
}
printf("number passed is_sorted : %i\n", npassed);
}
'if(a [i]> a [i + 1])'可能会超过数组的末尾 –
它肯定会在这种情况下过去:'is_sorted(c,5)' – babon
也被忽略'声明? –