[英]Control reaches end of non-void function in C
我想檢查數組是否以C或desc順序在C中排序。 這是使用mpicc -Wall -o文件file.c進行編譯的結果,因為我稍后在代碼中使用MPI庫。
mypractice1.c: In function ‘isSorted’:
mypractice1.c:38:1: warning: control reaches end of non-void function [-Wreturn-type]
}
^
/usr/bin/ld: unrecognised emulation mode: ypractice1
Supported emulations: elf_x86_64 elf32_x86_64 elf_i386 elf_iamcu i386linux elf_l1om elf_k1om i386pep i386pe
collect2: error: ld returned 1 exit status
這是我的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <mpi.h>
//Function to check the order
int isSorted(int size, int array[]) {
if(size<=1)
return 1; //is ordered
int i;
for(i = 1; i < size; i++){
if(array[i] >= array[i-1])
return 1; //is Sorted ascending
else if (array[i]< array[i-1])
return 2; //is sorted descending
else return 0; //is not ordered
}
}
如何解決此錯誤?
您說您有:
// Function to check the order
int isSorted(int size, int array[])
{
if (size <= 1)
return 1; // is ordered
for (int i = 1; i < size; i++)
{
if (array[i] >= array[i - 1])
return 1; // is Sorted ascending
else if (array[i] < array[i - 1])
return 2; // is sorted descending
else
return 0; // is not ordered
}
}
您不能只檢查前兩個值就返回。 您可能應該定義是否希望數據按升序或降序排序,並驗證是否已得到數據,但是如果您真的想分析數據的順序,則可以使用:
// Function to check the order
// 0 all equal
// 1 non-decreasing (ascending)
// 2 non-increasing (descending)
// -1 inconsistent (some ascending, some descending)
int isSorted(int size, int array[])
{
if (size <= 1)
return 1; // is ordered; deemed ascending
int num_eq = 0; // Number of adjacent pairs that are equal
int num_lt = 0; // Number of adjacent pairs sorted ascending
int num_gt = 0; // Number of adjacent pairs sorted descending
for (int i = 1; i < size; i++)
{
if (array[i] > array[i - 1])
num_gt++; // is sorted ascending
else if (array[i] < array[i - 1])
num_lt++; // is sorted descending
else
num_eq++; // is not ordered
}
assert(num_gt + num_lt + num_eq == size - 1);
if (num_gt == size - 1)
return 1; // ascending with all unique
if (num_lt == size - 1)
return 2; // descending with all unique
if (num_eq == size - 1)
return 0; // all rows equal
if (num_gt != 0 && num_lt != 0)
return -1; // inconsistent sorting
if (num_gt + num_eq == size - 1)
return 1; // ascending with some equal
if (num_lt + num_eq == size - 1)
return 2; // descending with some equal
return -1; // can't happen?
}
還有其他方法可以執行此操作,但是用尾注進行解釋非常簡單。 在函數尾部使用else if
鏈將是可行且明確的。 它有一些優點。 您可以對更多的返回值進行編碼,以區分嚴格遞增和非遞減還是嚴格遞減或非遞增。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.