前往
大廳
主題

【C#練習】找出程式碼的錯誤並修改(Microsoft Learn之習題)

小村 | 2023-01-19 23:25:26 | 巴幣 0 | 人氣 136

●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陳述式在閱讀上有區別

創作回應

相關創作

更多創作