计算(1,1,2,3,5,8,13.......N)的第N位的数值

using System; namespace CSharpDemo { class Demo { const int _val=30; static void Main() { xh1(); Console.WriteLine(dg(_val)); Console.WriteLine(xh2(_val)); } //递归取得第N个值 dg=递归 private static int dg(int val) { if (val == 0) return 0; if (val == 1) return 1; return dg(val – 1) + dg(val-2); } //for循环方式取得第N个值 xh=循环 //console.write只是为了验证一下输出看看正确不 private static void xh1() { int[] val=new int[_val]; val[0] = 1; val[1] = 1; Console.Write(“{0}/t{1}/t”,val[0],val[1]); for (int i = 2; i<val.Length; i++) { val[i] = val[i – 1] + val[i – 2]; Console.Write(“{0}/t”,val[i]); } } //只查看最后结果去掉中间过程方式 private static int xh2(int value) { int[] val = new int[value]; val[0] = 1; val[1] = 1; for (int i = 2; i < val.Length; i++) { val[i] = val[i – 1] + val[i – 2]; } return val[val.Length-1]; } } }

算法说明,第1位和第2位值定义出数组的数值后,比如第3位可用当前数组位置减去第二个位置加第一个位置的值相加(val[3] = val[3 – 1] + val[3 – 2])循环计算第N位的数值,递归可使代码简洁

点赞