C# 输入后输出控制台冻结

C# 输入后输出控制台冻结,c#,arrays,while-loop,unreachable-code,lcm,C#,Arrays,While Loop,Unreachable Code,Lcm,我一直在尝试编写代码来查找给定数组元素的LCM。我的代码如下所示 public long LcmOfArray(List<int> a) { long LCM = 1; bool divisible = false; int divisor = 2, count = 0; while (count != a.Count) { for (int i = 0; i < a.Count; i++) {

我一直在尝试编写代码来查找给定数组元素的LCM。我的代码如下所示

public long LcmOfArray(List<int> a) { long LCM = 1; bool divisible = false; int divisor = 2, count = 0; while (count != a.Count) { for (int i = 0; i < a.Count; i++) { if (a[i] == 0) { return 0; } if (a[i] < 0) { a[i] *= -1; } if (a[i] % divisor == 0) { divisible = true; a[i] /= divisor; } if (a[i] == 1) { count++; } } if (divisible) { LCM *= divisor; } else { divisor++; } } return LCM; } 公共长LCMOF阵列(列表a) { 长LCM=1; 布尔可除=假; 整数除数=2,计数=0; while(count!=a.count) { for(int i=0;i if (count == a.Count) { return LCM; } if(count==a.count) { 返回LCM; }
但现在编译器抛出一个错误,指出并非所有代码路径都返回一个值。有人能帮我解决代码中的错误吗?我是一名编码初学者。提前谢谢

while循环将持续运行,直到您给它一些东西来打破循环。在您的情况下,它打破循环的唯一方式似乎是在列表中的每一项都是1或达到0的情况下,因此根据列表的不同,它可能会也可能不会陷入无限循环中。例如,[i]=2似乎创建了一个无限循环。 另一个编译器错误是因为某些条件可能会跳过返回语句

if(count==a.Count)
{
   return LCM;
}
return void; // because what if count does not equal a.Count?

您应该将
bool divisible=false
整数计数=0在while循环中。既然你不能把
int count=0
在while循环之外您应该使用
while(true)
而不是
while(count!=a.count)
并将以下if语句放置在while循环的最后一个

if(count==a.count)
{
返回LCM;
}
以下是完整的方法:

公共静态长LCMOF数组(列表a)
{
长LCM=1;
整数除数=2;
while(true)
{
整数计数=0;
布尔可除=假;
for(int i=0;i
bool divisible=false这看起来不合适。既然你说你是开发新手,我建议你交个调试朋友。一次只做一行,看看你们的变量发生了什么,它在无限循环中的什么地方卡住了