我只是运动有一些问题..我必须编写一个程序,询问用户N的值,然后计算N!使用递归.我写了类似的东西
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);
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++);
}
}
}
Run Code Online (Sandbox Code Playgroud)
问题在于"int result = Count(ref N);" 我不知道为什么它不能转换为int.如果有人能帮助我,我将不胜感激.
因为它返回一个对象并且对象不能隐式转换为int,你可以做的就是更改方法的签名
private static int Count(ref int N)
Run Code Online (Sandbox Code Playgroud)
或者你可以做到这一点
int result = (int)Count(ref N);
Run Code Online (Sandbox Code Playgroud)
举一个简单的例子
//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
Run Code Online (Sandbox Code Playgroud)