如何修复错误“并非所有代码路径都返回值”? [英] How to fix error "not all code paths return a value"?

查看:392
本文介绍了如何修复错误“并非所有代码路径都返回值”?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好朋友,

我正在尝试编写一些能够从上到下计数的代码,从数字a到数字b,带有多个参数。但错误编译错误(第9行,第20行):'Program.count(int,int)':并非所有代码路径都返回一个值弹出,我知道它与需要放置有关返回在某些地方,但我不知道在哪里,我只是无法修复此错误。请帮助,非常感谢任何帮助。



我尝试过:



hello friends,
I am trying to write some code that is able to count both up and down, from number a to number b with multiple parameters. But the error "Compilation error (line 9, col 20): 'Program.count(int, int)': not all code paths return a value" pops up, I know that it has something to do with needing to put "return" in places but I have no idea where and I just can't fix this error. Please help, any assistance would be very much appreciated.

What I have tried:

using System;
					
public class Program
{
	public static void Main()
	{
		count(3, 10);
	}
	public static int count(int a, int b)
	{
		var number = 0;
		if (a < b) {
			while (a < b) {
				Console.WriteLine(number);
				number = number + 1;
			}
		}
		else {
			while (a > b) {
				Console.WriteLine(number);
				number = number - 1;
		  }		
	   }
	} 
}

推荐答案

错误信息意味着什么它说:通过你的方法至少有一条路线没有向调用者返回一个值。

在这种情况下,你的方法没有路由确实返回一个值!



在方法结尾处添加以下行:

The error message means exactly what it says: there is at least one route through your method that does not return a value to the caller.
In this case, there is at no route through your method that does return a value!

Add this line at the end of the method:
return number;


Quote:

我知道它与需要在某些地方放置返回有关,但我不知道在哪里

I know that it has something to do with needing to put "return" in places but I have no idea where



看看你的代码,你在哪里知道答案?

返回在该点之后和函数结束之前。

建议:尝试不同的解决方案,看看哪个有效或无效。这个尝试是试验和错误学习。



更改主要以获得答案并显示它:


Look at your code, where do you know the answer ?
The return goes after that point and before the end of the function.
Advice: try different solutions ans see which one works or don't. This try is "Trial and error learning".

Change main to get the answer and display it:

public static void Main()
{
    int result= count(3, 10);
    Console.WriteLine("Result is ");
    Console.WriteLine(result);
}


您的问题有两种选择:

如果您只想打印行结果

There are two alternatives to your problem:
If you only want to print your result as you do with the lines
Console.WriteLine(number);



没有必要你的方法返回一个值。在这种情况下,您应该将方法的类型更改为


there is no need for your method to return a value. In this case you should change your method's type to

public static void count(int a, int b)



如果您需要调用方法的结果,OriginalGriff会为您提供解决方案。


If you need the result where you call the methode, OriginalGriff gave you the solution.


这篇关于如何修复错误“并非所有代码路径都返回值”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆