首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

VB.NET 找出 10 個數中的最大值及其位置:正確邏輯與代碼實現

     編輯:程式設計綜合問答

問題分析

原代碼存在邏輯混淆:A/B 兩個數組用途不明,循環體未正確更新最大值與索引。

正確算法邏輯

  1. 初始化 maxVal = Int32.MinValue, maxIndex = -1
  2. 遍歷 10 次:讀入數值 → 若 > maxVal 則更新 maxVal 與 maxIndex
  3. 輸出結果

VB.NET 完整實現 (控制台程序)

Module 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 循環直到合法
多個相同最大值本邏輯記錄**第一次**出現位置;若需最後一次,改為 = 判斷

進階:使用 LINQ (VB.NET 語法)

Dim maxVal = numbers.Max()
Dim maxIndex = numbers.ToList().FindIndex(Function(x) x = maxVal)
' 或
Dim maxIndex = Array.IndexOf(numbers, maxVal)

總結

核心邏輯極簡:**單次遍歷、雙變量維護**。避免引入無關數組 (如原代碼的 A/B),保持代碼最小認知負荷。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved