[英]Equal to, less or greater then - what path am I missing? Why does is say "not all code paths return a value"?
我想知道為什么這會給我一條錯誤消息。 缺少的路徑是什么? 等於,小於或大於-應該涵蓋所有路徑,對嗎? PS。 我是編程新手。
public string LargestNumber(int num1, int num2)
{
if (num1 > num2)
return("number 1 is the greatest!");
if (num1 < num2)
return("number 2 is the greatest!");
if (num1 == num2)
return("Both are equal!");
}
好吧,在許多情況下(不是int
,而是說double
),我們可以有無法比較的值,我們不能說它們是否相等或者其中一個更大或更小。 編譯器知道它(但它不知道確切的int
比較實現)所以它抱怨:如果num1
和num2
無法比較怎么辦? 並且所有num1 > num2
, num1 < num2
, num1 == num2
都返回false
? 在這種情況下應該退回什么?
最簡單的解決方案是刪除最后一個條件:
public string LargestNumber(int num1, int num2)
{
if (num1 > num2)
return("number 1 is the greatest!");
if (num1 < num2)
return("number 2 is the greatest!");
// We know, that there's one option here : to be equal
// Compiler doesn't know that all ints are comparable
return("Both are equal!");
}
請注意,如果使用相同的代碼但要double
,則投訴是有道理的。 存在無與倫比的double
值:
public string LargestNumber(double num1, double num2)
{
if (num1 > num2)
return("number 1 is the greatest!");
if (num1 < num2)
return("number 2 is the greatest!");
if (num1 == num2)
return("Both are equal!");
return "Oops!";
}
演示:
// double.NaN - Not a Number
// if floating point value is not a number, we can't just compare it!
// all >, <, == will return false!
Console.Write(LargestNumber(double.NaN, double.NaN));
Output:
Oops!
我現在已經更新了它,它似乎工作..
public string SumOfNumber(int num1, int num2)
{
if (num1 > num2)
return("number 1 is the greatest!");
else if (num1 < num2)
return("number 2 is the greatest!");
else
return("Both are equal!");
}
編譯器不夠聰明(更好的是:它不會做所有的工作)來檢查這個值永遠不會大於/小於/等於另一個值是不可能的。 它說你:做你的工作並確保它是不可能的。 不過很容易修復:
只需刪除最后一個if
:
public string LargestNumber(int num1, int num2)
{
if (num1 > num2)
return "number 1 is the greatest!";
if (num1 < num2)
return "number 2 is the greatest!";
return "Both are equal!";
}
您絕對應該在末尾使用帶有 else 子句的 else if 結構。 您的代碼中沒有“無論如何”都會執行的默認路徑
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.