如何使用 C# 打印前十个斐波那契数?
要显示前十个数字,首先设定前两个数字。
int val1 = 0, val2 = 1;
现在,使用 for 循环从 2 到 10,以显示前十个斐波那契数 -
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
广告