●Question
請修正以下程式的問題使其順利運作:
int[] numbers = { 4, 8, 15, 16, 23, 42 };
foreach (int number in numbers)
{
int total;
total += number;
if (number == 42)
{
bool found = true;
}
}
if (found)
{
Console.WriteLine("Set contains 42");
}
Console.WriteLine($"Total: {total}");
●Solution
int[] numbers = { 4, 8, 15, 16, 23, 42 };
int total = 0;
bool found = false;
foreach (int number in numbers)
{
total += number;
if (number == 42) found = true;
}
if (found)
{
Console.WriteLine("Set contains 42");
}
Console.WriteLine($"Total: {total}");
讓程式運作起來的改動:
1.將 total 和 found 變數移至 foreach 陳述式外部
2.使用合理的預設值來將 total 與 found 變數初始化
表達上的改動:
1.foreach陳述式內部的if陳述式,移除程式碼區塊和多餘的換行字元,以跟下面的if陳述式在閱讀上有區別