我写了下面这个小程序来打印斐波那契数列:
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();
}
编译错误信息为:
无法隐式将类型“int”转换为“short”。存在显式转换(是否缺少强制转换?)
既然涉及的所有内容都是Int16(短整型),为什么会有任何隐式转换呢?更具体地说,为什么会在此处失败(而不是最初将int分配给变量时)?
希望能够得到解释。
Int16
,以便当Int16
的宽度无法容纳太大的值时,我可以看到序列重新开始。 - m.edmondson