![](/img/trans.png)
[英]Switch Statement Error **control reaches end of non-void function [-Werror=return-type]**
[英]How to fix "error: control reaches end of non-void function [-Werror=return-type]" at HackerRank?
好的,已經提供了很多答案,但我似乎無法真正找到解決方案。
我們的任務是找到四個整數中最大的一個。
https://www.hackerrank.com/challenges/functions-in-c/problem
當我運行以下代碼時:
#include <stdio.h>
/*
int max_of_four(int a, int b, int c, int d)
{
if(a>b && a>c && a>d)
return a;
else if(b>a && b>c && b>d)
return b;
else if(c>a && c>b && c>d)
return c;
else
return d;
}
*/
int max_of_four(int a, int b, int c, int d)
{
if(a>b)
{
if(a>c)
{
if(a>d)
return a;
}
}
else if(b>c)
{
if(b>d)
return b;
}
else if(c>d)
return c;
else
return d;
}
int 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);
return 0;
}
我在 HackerRank返回此錯誤:
Solution.c: In function ‘max_of_four’:
Solution.c:45:1: error: control reaches end of non-void function [-Werror=return-type]
}
^
cc1: some warnings being treated as errors
但是上面的代碼在 Dev-C++ 5.11 上運行時可以完成它的工作。
如果我們使用注釋max_of_four
的函數,並注釋掉后一個,工作也完成了。
如果有人能讓我知道如何調整max_of_four
以使代碼正常工作,我將不勝感激。
導致錯誤的原因是什么?
這是錯誤還是警告? 如果是這樣,為什么警告被視為錯誤?
當函數不是 void 並且您使用if
語句返回值時,您必須檢查是否真的處理了每個案例。 在這種情況下,最后一個 else 無法確保這一點,因為您使用了沒有else
嵌套語句。
這是一個固定版本:
int max_of_four(int a, int b, int c, int d)
{
if(a>b)
{
if(a>c)
{
if(a>d)
return a;
}
}
if(b>c) //<====== I removed the else here to fix the implicit
// else of the previous form that was not handled
{
if(b>d)
return b;
}
if(c>d) //<===== Idem
return c;
else
return d;
}
但是請注意,嵌套if
in you 函數可以替換為and
,這會更緊湊:
int max_of_four(int a, int b, int c, int d)
{
if (a>b && a>c && a>d) return a;
else if(b>c && b>d) return b; // Here the else keys are kept even
else if(c>d) return c; // if they are not strictly necessary
else return d; // because of the return
}
最后,編寫以下代碼也更具可重用性:
int max_of_two(int a, int b) { return a > b ? a : b; }
因為這樣你就可以將它重用於任意數量的參數:
int max_of_three(int a, int b, int c) {
return max_of_two(max_of_two(a, b), c);
}
int max_of_four(int a, int b, int c, int d) {
return max_of_two(max_of_two(a, b), max_of_two(c, d));
}
//And so on
@dslr已經為上面提出的所有問題提供了最佳答案。
對於任何即將到來的讀者, @Carcigenicate評論的內容可以從下面的代碼中理解:
int max_of_four(int a, int b, int c, int d)
{
if(a>b)
{
if(a>c)
{
if(a>d)
return a;
else
return d;
}
else if(c>d)
return c;
else
return d;
}
else if(b>c)
{
if(b>d)
return b;
else
return d;
}
else if(c>d)
{
return c;
}
else
return d;
}
代碼在 HackerRank 上運行流暢,沒有出現任何錯誤。
這可能就是@Carcigenicate所說的“循環遍歷數組”的意思:
int max_of_four(int a, int b, int c, int d)
{
int i;
int arr[4]={a,b,c,d};
int max=arr[0];
for(i=1;i<4;i++)
{
if(max<arr[i])
max=arr[i];
}
return max;
}
謝謝大家。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.