gpt4 book ai didi

vb.net - 有什么方法可以使用循环简化我的代码。在 Visual Basic 中

转载 作者:行者123 更新时间:2023-12-02 04:33:45 24 4
gpt4 key购买 nike

我有一个程序,可以查看为候选人输入的选票,并根据得分最低的人确定获胜者。因为用户输入从 1 到 5 的偏好,其中 1 是最喜欢的,5 是最不喜欢的。如果平局,则 1 最多的候选人获胜,如果仍然平局,则其 2 最多的候选人获胜。我有一个程序,但想知道在继续重复代码以检查谁获得最多 2 等之前是否可以简化它。这就是我到目前为止所拥有的。

    If candidate1 < candidate2 And candidate1 < candidate3 And candidate1 < candidate4 And candidate1 < candidate5 Then
MsgBox("The winner is" & LblCand1.Text)
ElseIf candidate2 < candidate1 And candidate2 < candidate3 And candidate2 < candidate4 And candidate2 < candidate5 Then
MsgBox("The winner is" & lblCand2.Text)
ElseIf candidate3 < candidate2 And candidate3 < candidate1 And candidate3 < candidate4 And candidate3 < candidate5 Then
MsgBox("The winner is" & lblCand3.Text)
ElseIf candidate4 < candidate2 And candidate4 < candidate3 And candidate4 < candidate1 And candidate4 < candidate5 Then
MsgBox("The winner is" & lblCand4.Text)
ElseIf candidate5 < candidate2 And candidate5 < candidate3 And candidate5 < candidate4 And candidate5 < candidate1 Then
MsgBox("The winner is" & lblCand5.Text)
ElseIf C1V1s > C2V1s And C1V1s > C3V1s And C1V1s > C4V1s And C1V1s > C5V1s Then
MsgBox("The winner is" & LblCand1.Text)
ElseIf C2V1s > C1V1s And C2V1s > C3V1s And C2V1s > C4V1s And C2V1s > C5V1s Then
MsgBox("The winner is" & lblCand2.Text)
ElseIf C3V1s > C1V1s And C3V1s > C2V1s And C3V1s > C4V1s And C3V1s > C5V1s Then
MsgBox("The winner is" & lblCand3.Text)
ElseIf C4V1s > C1V1s And C4V1s > C2V1s And C4V1s > C3V1s And C4V1s > C5V1s Then
MsgBox("The winner is" & lblCand4.Text)
ElseIf C5V1s > C1V1s And C5V1s > C2V1s And C5V1s > C3V1s And C5V1s > C4V1s Then
MsgBox("The winner is" & lblCand5.Text)
End If

最佳答案

我建议您创建一个类Candidate,其中包含每个候选人的分数和名称:

Class Candidate
Implements IComparable(Of Candidate)

Public Property Score As Integer
Public Property Name As String

Public Function CompareTo(other As Candidate) As Integer Implements IComparable(Of Candidate).CompareTo
If (other.Score > Me.Score) Then
Return -1
ElseIf (other.Score = Me.Score) Then
Return 0
Else
Return 1
End If
End Function
End Class

然后,如果您有候选实例的集合,则可以执行以下操作:

Dim myCandidates As New List(Of Candidate)
'fill your list with instances somehow...
MsgBox(String.Format("The winner is {0}", myCandidates.Min().Name))

请注意,Candidate 类必须实现 the IComparable(Of T) interface因此实例知道如何通过 Min() 方法比较自身。

关于vb.net - 有什么方法可以使用循环简化我的代码。在 Visual Basic 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33693308/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com