C# why object can't be converted to int
我只是运动有点问题。我必须编写一个程序,要求用户输入n的值,然后计算n!使用递归。我写了类似的东西
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | namespace ConsoleApplication19 { class Program { static void Main(string[] args) { Console.WriteLine("This program will calculate a factorial of random number. Please type a number"); String inputText = Console.ReadLine(); int N = int.Parse(inputText); </p> <wyn> String outputText ="Factorial of" + N +"is:"; int result = Count(ref N); Console.WriteLine(outputText + result); Console.ReadKey(); } private static object Count(ref int N) { for (int N; N > 0; N++) { return (N * N++); } } } |
问题出在"i n t result=count(ref n);"一行,我不知道为什么它不能转换成int,如果有人能帮助我,我将不胜感激。
因为它返回的是一个对象,而对象不能隐式转换为int,所以您可以做的是像这样更改方法的签名
1 | private static int Count(ref int N) |
或者你可以这样做
1 | int result = (int)Count(ref N); |
举个简单的例子
1 2 3 4 5 6 7 8 9 10 | //this is what you are doing object obj = 1; int test = obj; //error cannot implicitly convert object to int. Are you missing a cast? //this is what needs to be done object obj = 1; int test = (int)obj; //perfectly fine as now we are casting // in this case it is perfectly fine other way around obj = test; //perfectly fine as well |
我想是因为你的方法类型是"object",应该是"int"。
是的,正如前面的回复所提到的,您不需要引用,您需要返回一个int。您的问题说您需要使用递归,但您使用的是for循环?
下面是如何编写阶乘递归方法:
1 2 3 4 5 6 | public long Factorial(int n) { if (n == 0) //base return 1; return n * Factorial(n - 1); } |