要显示前十个数字,请首先设置前两个数字。
int val1 = 0, val2 = 1;
现在,使用从2到10的for循环,显示前十个斐波那契数-
for(i=2;i<10;++i) { val3 = val1 + val2; Console.Write(val3+" "); val1 = val2; val2 = val3; }
以下是显示前十个斐波那契数字的完整代码-
using System; public class Demo { public static void Main(string[] args) { int val1 = 0, val2 = 1, val3, i, n; n = 10; Console.WriteLine("1st ten Fibonacci numbers:"); Console.Write(val1+" "+val2+" "); for(i=2;i<n;++i) { val3 = val1 + val2; Console.Write(val3+" "); val1 = val2; val2 = val3; } } }
输出结果
1st ten Fibonacci numbers: 0 1 1 2 3 5 8 13 21 34