@kikurageoisii

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

c#初心者 見たことないエラ〜が出る 助けて

Q&A

Closed

フィボナッチ数列の第20項までを、配列を使って出力しようとしたところ、以下のようなエラーが出ました。

indexと書いてあるので、forのところでiのはんいをミスったかなと思ったのですがそんな様子がなく困ってます。

有識者の方教えてください

###エラー
Unhandled Exception:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at test.Main () [0x00017] in :0
[ERROR] FATAL UNHANDLED EXCEPTION: System.IndexOutOfRangeException: Index was outside the bounds of the array.
at test.Main () [0x00017] in :0

該当するソースコード

using System;

class test
{
static void Main()
{
int[] a = new int[20];
a[0] = 1;
a[1] = 1;

	for(int i=2; i<=a.Length; ++i)
	{
		a[i] = a[i-1] + a[i-2];
		      Console.WriteLine(a[i]);
	}
}

}

0 likes

1Answer

a配列の長さ(Length)は20個ですが、要素番号的には0~19になります。

for文でi<=a.Lengthとしてしまっているため、iが20になるまでループを回していることになります。

正しくは
for(int i=2; i<a.Length; ++i)
=を無くせば19までのループとなり、エラーにならなくなるはずです。

1Like

Comments

  1. @kikurageoisii

    Questioner

    動きました!!
    配列番号は0スタートだから20番目は[19]だったってことですね!すっきりしました
    ありがとうございます!!!

Your answer might help someone💌