[英]I am getting a 'not all code paths return a value' error in my c# code
[英]Why am I getting this error: not all code paths return a value?
嗨,我是C#的新手,正在嘗試編碼,但是遇到錯誤有人可以幫助我嗎,這是我做錯了什么?
using System;
using System.Collections.Generic;
using System.Text;
namespace hodder
{
class Program
{
public static void Main()
{
isHodder(3);
}
static int isHodder(int n)
{
int k = n;
for (int i = 2; i <= n / 2;i++ )
{
if ((n % 1) == 0)
{
return 0;
}
else
{
for (int j = 2; j <= k;j++ )
{
if (n == (2^ j) - 1)
{
return 1;
}
else
{
return 0;
}
k=(2^j)-1;
}
}
}
}
}
}
我在“ static int isHodder(int n)”上收到錯誤:'hodder.Program.isHodder(int)':並非所有代碼路徑都返回值
和“ k =(2 ^ j)-1”上的“檢測到無法訪問的代碼”
第一個錯誤是“並非所有代碼路徑都返回一個值”,這意味着存在一條代碼可以遵循的路徑,在該路徑中不會返回任何值(即:調用isHodder(1))。 您需要在for循環之外返回一些值。 另外,由於在第二個for循環中有一個if / else塊,所以該行
k=(2^j)-1;
永遠不會被執行。
static int isHodder(int n)
{
int k = n;
for (int i = 2; i <= n / 2; i++)
{
if ((n % 1) == 0)
{
return 0;
}
else
{
for (int j = 2; j <= k; j++)
{
if (n == (2 ^ j) - 1)
{
return 1;
}
else
{
return 0;
}
k = (2 ^ j) - 1;
}
}
}
return 0;
}
這行是高度可疑的:
if ((n % 1) == 0)
如果我呼叫isHodder(1)
怎樣? 我可以到達哪個退貨單?
我們可能根本不會進入for循環(或者,如果確實輸入了它,編譯器無法確定在離開循環之前我們是否會返回return語句)。
對於此問題,如果函數未返回任何值,則必須使用void,否則必須在函數末尾定義一個返回值。
@jalf:關於2 <= n / 2(即4 <= n)的情況是正確的。 在這種情況下,您永遠不會進入for循環,因此您需要在for
之后返回。
正如@Kenny所建議的,
if ((n % 1) == 0)
是可疑的。 n%1始終== n,因此條件只有在n == 0時才為真。但是,由於條件不測試循環中的任何變化,因此看起來也可能是錯字。 你的意思是
if ((n % i) == 0)
?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.