数组索引问题
数列:a1=1;a2=2;an=a(n-2)+a(n-1)
通过程序验证,当n趋向于无穷大时,数列前后项的比值无限接近0.618
以下是我写的:
int n = int.Parse(textBox1.Text);
int[] a=new int[n];
a[1] = 1;
a[2] = 1;
for (int i = 3; i <= n; i++)
{
a[n] = a[n - 2] + a[n - 1];
}
float b = a[n - 1] / a[n];
label1 .Text =b.ToString ( "f4 ");
------解决方案--------------------要想足够的精度,而且N还需要比较大,仅仅用int是不够的,另外循环中的变量n应改成i,最终代码如下:
int n = int.Parse(textBox1.Text);
double[] a = new double[n + 1];
a[1] = 1;
a[2] = 1;
for (int i = 3; i <= n; i++)
{
a[i] = a[i - 2] + a[i - 1];
}
double b = (double)a[n - 1] / a[n];
label1.Text = b.ToString( "f4 ");