簡體   English   中英

控制到達非空函數錯誤的結尾

[英]control reaches end of non-void function error

我剛開始在Hackerrank練習,遇到了這個錯誤。

問題是使用函數找到 4 個數字中的最大值。

#include <stdio.h>
/*
Add `int max_of_four(int a, int b, int c, int d)` here.
*/

void main()
{

    int a, b, c, d;
    scanf("%d %d %d %d", &a, &b, &c, &d);
    int ans = max_of_four(a, b, c, d);
    printf("%d", ans);

}
int max_of_four(int a,int b,int c,int d)
{
     if(a>b&& a>c && a>d) 

       return (a);
       else if(a<b&& b>c && b>d)
       return (b);
       else if(c>b&& a<c && c>d)
       return (c);
       else if(d>b&& d>c && a<d)
       return (d);
}

有可能在沒有看到返回的情況下到達此函數的末尾。
這就是編譯器告訴你的。
這就是原因。

int max_of_four(int a,int b,int c,int d)
{
     if(a>b&& a>c && a>d) 
       return (a);
     else if(a<b&& b>c && b>d)
       return (b);
     else if(c>b&& a<c && c>d)
       return (c);
     else if(d>b&& d>c && a<d)
       return (d);
     /* so what if none of above applies? e.g. if some are equal? */
}

可以通過將所有>替換為>= ,將所有<替換為<=並刪除最后一個if() ,即把else if變成else 即使最大的數字出現了兩次或四次,你也會發現它是這樣的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM