我试图在不使用循环的情况下检查数组是否已排序。它工作正常,即。如果我有一个包含按升序排列的元素的数组,则 printf 会执行,因为我得到“已排序”。但是
printf("数组 1 返回:%d\n\n", sortCheck(arr1, SORTED1));
返回 0?为什么是这样?
谢谢。这是完整的代码。
#include<stdio.h>
const int SORTED1 = 5;
int sortCheck (int arr[], int arrSize);
int indexCounter = 0;
int main()
{
int arr1[] = {1,2,3,4,5};
printf("Array 1: \n");
printf("Array 1 returns: %d \n\n", sortCheck(arr1, SORTED1));
indexCounter = 0;
return 0;
}
int sortCheck(int arr[], int arrSize)
{
if ( (arr[indexCounter]==arr[arrSize-1]) && (indexCounter==arrSize-1) )
{
printf("Sorted. \n");
return 1;
}
if ( arr[indexCounter] <= arr[indexCounter+1] )
{
indexCounter++;
sortCheck(arr, arrSize);
}
else
{
printf("Not sorted.");
return 0;
}
}
最佳答案
由于缺少 return
语句,您看到了未定义的行为。
if ( arr[indexCounter] <= arr[indexCounter+1] )
{
indexCounter++;
// Problem. Missing return.
sortCheck(arr, arrSize);
}
将违规行更改为:
return sortCheck(arr, arrSize);
关于c - C 中的函数没有返回正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28978153/