原代碼存在邏輯混淆:A/B 兩個數組用途不明,循環體未正確更新最大值與索引。
maxVal = Int32.MinValue, maxIndex = -1Module Module1
Sub Main()
Dim numbers(9) As Integer
Dim maxVal As Integer = Integer.MinValue
Dim maxIndex As Integer = -1
Console.WriteLine("請輸入 10 個整數:")
For i As Integer = 0 To 9
Dim input As String = Console.ReadLine()
While Not Integer.TryParse(input, numbers(i))
Console.Write("輸入無效,請重新輸入整數: ")
input = Console.ReadLine()
End While
If numbers(i) > maxVal Then
maxVal = numbers(i)
maxIndex = i
End If
Next
Console.WriteLine($"最大值: {maxVal}")
Console.WriteLine($"位置 (0-based 索引): {maxIndex}")
Console.WriteLine($"位置 (1-based 第幾個): {maxIndex + 1}")
Console.WriteLine("所有數據: " & String.Join(", ", numbers))
Console.ReadKey()
End Sub
End Module
| 易錯點 | 正確做法 |
|---|---|
| 未初始化 maxVal | 用 Integer.MinValue 確保任何輸入都能更新 |
| 索引從 1 開始 | 數組索引從 0 起,輸出時可 +1 符合人類習慣 |
| 輸入驗證缺失 | 用 Integer.TryParse 循環直到合法 |
| 多個相同最大值 | 本邏輯記錄**第一次**出現位置;若需最後一次,改為 = 判斷 |
Dim maxVal = numbers.Max()
Dim maxIndex = numbers.ToList().FindIndex(Function(x) x = maxVal)
' 或
Dim maxIndex = Array.IndexOf(numbers, maxVal)
核心邏輯極簡:**單次遍歷、雙變量維護**。避免引入無關數組 (如原代碼的 A/B),保持代碼最小認知負荷。