我想使用IF语句和NESTED IF语句找到它。我知道如何找到3个数字中最大的数字,但不能做到5.我想遵循与下面代码相同的概念:
Dim number1, number2, number3, largest as integer
number1= 2
number 2= 7
number3= 14
If number1>number2 then
if number1>number 3 then
largest= number1
else
largest= number3
End If
Else If number2> number3 then
largest= number2
else
largest number3
End If
label1.text= largest
答案 0 :(得分:1)
通过将每个数字与最大数字进行比较,并且仅在数字较大的情况下进行分配,您将最终分配给最大数字。
Dim number1, number2, number3, largest As Integer
number1 = 2
number2 = 7
number3 = 14
' if 2 > 0 then largest = 2
If number1 > largest Then largest = number1
' if 7 > 2 then largest = 7
If number2 > largest Then largest = number2
' if 14 > 7 then largest = 14
If number3 > largest Then largest = number3
label1.text = largest
答案 1 :(得分:0)
逻辑需要一些重新思考。目前,您正在使用蛮力方法,正如您已经发现的那样,原始集合越大,就越复杂。并且你的解决方案不是真正可维护的 - 如果你想要4个数字,10个数字等,你将不得不一直重写代码。
现代编码语言包括循环和集合,以使我们的生活更轻松。
Function MyMax(Numbers() As Long) As String
Dim largest As Long = Long.MinValue
If Numbers.Count > 0 Then ' it is ok to find the maximum from a single number!
For iterator = 0 To Numbers.Count - 1
If Numbers(iterator) > largest Then largest = Numbers(iterator)
'largest = If(Numbers(iterator) > largest, Numbers(iterator), largest) ' another way of achieving the line above
Next
Return largest.ToString
Else
Return "Error - no numbers to check!"
End If
End Function
Sub testMyMax()
Debug.Print(MyMax({2, 7, 14}))
End Sub