C# compiler error: quot;not all code paths return a valuequot;(C# 编译器错误:“并非所有代码路径都返回值;)
问题描述
我正在尝试编写返回给定整数是否可被 1 到 20 整除的代码,
但我不断收到以下错误:
I'm trying to write code that returns whether or not a given integer is divisible evenly by 1 to 20,
but I keep receiving the following error:
错误 CS0161:ProblemFive.isTwenty(int)":并非所有代码路径都返回值
error CS0161: 'ProblemFive.isTwenty(int)': not all code paths return a value
这是我的代码:
public static bool isTwenty(int num)
{
for(int j = 1; j <= 20; j++)
{
if(num % j != 0)
{
return false;
}
else if(num % j == 0 && num == 20)
{
return true;
}
}
}
推荐答案
你缺少一个 return
语句.
当编译器查看您的代码时,它会看到第三条路径(您未编写代码的 else
)可能会发生但不返回值.因此并非所有代码路径都返回值
.
When the compiler looks at your code, it's sees a third path (the else
you didn't code for) that could occur but doesn't return a value. Hence not all code paths return a value
.
对于我建议的修复,我在循环结束后放置了一个 return
.另一个明显的地方 - 将具有 return
值的 else
添加到 if-else-if
- 会破坏 for
循环.
For my suggested fix, I put a return
after your loop ends. The other obvious spot - adding an else
that had a return
value to the if-else-if
- would break the for
loop.
public static bool isTwenty(int num)
{
for(int j = 1; j <= 20; j++)
{
if(num % j != 0)
{
return false;
}
else if(num % j == 0 && num == 20)
{
return true;
}
}
return false; //This is your missing statement
}
这篇关于C# 编译器错误:“并非所有代码路径都返回值";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C# 编译器错误:“并非所有代码路径都返回值";


基础教程推荐
- 全局 ASAX - 获取服务器名称 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01