2013-03-26 45 views
4

這是在3尋找最大碼,但我想要的代碼查找最大amoung 5:你如何在vb.net中找到5個最大的數字?

Dim a, b, c As Integer 

a = InputBox("enter 1st no.") 
b = InputBox("enter 2nd no.") 
c = InputBox("enter 3rd no.") 

If a > b Then 
    If a > c Then 
     MsgBox("A is Greater") 
    Else 
     MsgBox("C is greater") 
    End If 
Else 
    If b > c Then 
     MsgBox("B is Greater") 
    Else 
     MsgBox("C is Greater") 
    End If 
End If 

回答

3

正如David建議的那樣,將您的值保存在列表中。這比取消單個變量更容易,並且可以根據請求擴展到多個值(高達數百萬個值)。

如果你需要保持各個變量由於某種原因,這樣做:

Dim max As Integer = a 
Dim name As String = "A" 
If b > max Then 
    max = b 
    name = "B" 
End If 
If c > max Then 
    max = c 
    name = "C" 
End If 
If d > max Then 
    max = d 
    name = "D" 
End If 
MsgBox(name & " is greater") 
... 
+0

Greate !!這是我需要的 – sangeen 2013-03-28 18:48:00

11

把值到一個數組並使用the Max function on IEnumerable

'Requires Linq for Max() function extension 
Imports System.Linq 
'This is needed for List 
Imports System.Collections.Generic 

' Create a list of Long values. 
Dim longs As New List(Of Long)(New Long() _ 
            {4294967296L, 466855135L, 81125L}) 

' Get the maximum value in the list. 
Dim max As Long = longs.Max() 

' Display the result. 
MsgBox("The largest number is " & max) 

' This code produces the following output: 
' 
' The largest number is 4294967296 
+0

要回答的任擇議定書應返回的最大的指數。 – bradgonesurfing 2013-03-26 18:39:55

+0

@bradgonesurfing:我想過,是的。真的,這只是從鏈接的MSDN頁面複製/粘貼。雖然從OP的代碼中並不清楚他實際上在做什麼或爲什麼。然而,很明顯,有很大的改進空間。 – David 2013-03-26 18:48:56

+0

確實是一個新手,但他的代碼確實給出了最大數字的字母索引。它實際上並不像你想象的那樣在IEnumerable上做的微不足道。 Google MaxBy – bradgonesurfing 2013-03-26 19:04:52

1

一個簡單的解決方案,你,

Dim xMaxNo As Integer 
Dim xTemp As Integer 

For i as integer = 1 To 5 
    xTemp = InputBox("enter No: " & i) 
    xMaxNo = if(xTemp > xMaxNo, xTemp, xMaxNo) 
Next 

MsgBox("The Highest Number is " & xMaxNo) 
+0

這簡單而優雅。 – Jeremy 2016-08-04 20:28:26

相關問題