无法将类型'int'隐式转换为'short'

m.e*_*son 39 c# int short

我编写了以下小程序来打印出Fibonacci序列:

static void Main(string[] args)
{
    Console.Write("Please give a value for n:");
    Int16 n = Int16.Parse(Console.ReadLine());

    Int16 firstNo = 0;
    Int16 secondNo = 1;

    Console.WriteLine(firstNo);
    Console.WriteLine(secondNo);

    for (Int16 i = 0; i < n; i++)
    {
        //Problem on this line                    
        Int16 answer = firstNo + secondNo;

        Console.WriteLine(answer);

        firstNo = secondNo;
        secondNo = answer;
    }

    Console.ReadLine();

}
Run Code Online (Sandbox Code Playgroud)

编译消息是:

无法将类型'int'隐式转换为'short'.存在显式转换(您是否错过了演员?)

由于涉及的所有内容都是Int16(简称),那么为什么会有任何隐式转换?更具体地说,为什么在这里失败(而不是最初为变量赋予int)?

非常感谢您的解释.

m-y*_*m-y 80

Microsoft 在执行add函数时将Int16变量转换为Int32.

更改以下内容:

Int16 answer = firstNo + secondNo;
Run Code Online (Sandbox Code Playgroud)

成...

Int16 answer = (Int16)(firstNo + secondNo);
Run Code Online (Sandbox Code Playgroud)


Mar*_*age 5

添加两个Int16值会产生一个Int32值.你必须把它投射到Int16:

Int16 answer = (Int16) (firstNo + secondNo);
Run Code Online (Sandbox Code Playgroud)

您可以通过切换所有号码来避免此问题Int32.