正確的程序:
int[] A = { 3, 6, 4, 9, 10, 1, 2, 8 };
int myNumber;
int length = A.Length;
Console.WriteLine("enter your number");
myNumber = Convert.ToInt32(Console.ReadLine());
// ADDED
bool found = false;
for (int i = 0; i < length; i++)
{
if (myNumber == A[i])
{
found = true; // ADDED
// On the far right of next row: Fixed A[i] -> i
Console.WriteLine("the numer" + myNumber + "is present in the array at the index" + " " + i);
break;
}
}
// ADDED
if (!found)
{
Console.WriteLine("the number you entered are not found");
}
Console.ReadKey();
我希望/想你可以看到/理解沒有幫助的差異。
我補充一點,有解決問題的第二種方法:
int[] A = { 3, 6, 4, 9, 10, 1, 2, 8 };
int myNumber;
int length = A.Length;
Console.WriteLine("enter your number");
myNumber = Convert.ToInt32(Console.ReadLine());
// MOVED OUTSIDE FOR
int i = 0;
for (; i < length; i++)
{
if (myNumber == A[i])
{
// On the far right of next row: Fixed A[i] -> i
Console.WriteLine("the numer" + myNumber + "is present in the array at the index" + " " + i);
break;
}
}
// ADDED
if (i == length)
{
Console.WriteLine("the number you entered are not found");
}
Console.ReadKey();
看到區別:found
是沒有必要的,我們只使用i
變量,有其「範圍」擴大。
索引是''我''不是''a [i]'' –