如何使用 C# 打印前十个斐波纳契数?
首先,设置前两个数字,以显示前十个数字。
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
广告