您不应该检查
temp != i
但是
==
仅在循环内:
// array is double[] - item is double
foreach (double item in array) {
// item found, we shall report and exit the method
if (item == temp) { // <- dubious: we should check doubles with tolerance
Console.WriteLine("The number is in the array.");
return; // <- not break
}
}
// entire array has been scanned, no item found
Console.WriteLine("The number is not part of the array.");
如果你不想
return
,但坚持
break
:
bool inTheArray = false;
foreach (double item in array)
if (item == test) {
inTheArray = true;
break;
}
Console.WriteLine(inTheArray
? "The number is in the array."
: "The number is not part of the array.");