2
這是我第一次在這裏發佈。我正在爲我參加的課程制定一些計劃。我需要獲得英里和加侖,然後計算每個條目的MPG。我有這方面的想法。我似乎無法得到的是底部的總數。我需要添加每個ListBox中所有項目的總和,並在每次點擊按鈕時計算總的MPG。這是我的代碼到目前爲止。計算列表框中的項目總和 - Visual Basic
Public Class MilesPerGallon
Private Sub calculateMPGButton_Click(sender As System.Object,
ByVal e As System.EventArgs) Handles calculateMPGButton.Click
Dim miles As Double ' miles driven
Dim gallons As Double ' gallons used
Dim totalMiles As Double ' total miles driven
Dim totalGallons As Double ' total gallons used
Dim counter As Integer
miles = milesDrivenTextBox.Text ' get the miles driven
gallons = gallonsUsedTextBox.Text ' get the gallons used
If milesDrivenTextBox.Text <> String.Empty Then
' add miles to the end of the milesListBox
milesListBox.Items.Add(milesDrivenTextBox.Text)
milesDrivenTextBox.Clear() ' clears the milesDrivenTextBox
End If
If gallonsUsedTextBox.Text = 0 Then
' do not divide by 0 and alert 0
gallonsUsedTextBox.Text = "Cannot equal 0"
End If
If gallonsUsedTextBox.Text > 0 Then
' add gallons to the end of the gallonsListBox
gallonsListBox.Items.Add(gallonsUsedTextBox.Text)
mpgListBox.Items.Add(String.Format("{0:F}", miles/gallons))
gallonsUsedTextBox.Clear() ' clears the gallonsUsedTextBox
End If
totalMiles = 0
totalGallons = 0
counter = 0
Do While totalMiles < milesListBox.Items.Count
miles = milesListBox.Items(totalMiles)
totalMiles += miles
counter += 1
Do While totalGallons < gallonsListBox.Items.Count
gallons = gallonsListBox.Items(totalGallons)
totalGallons += gallons
counter += 1
Loop
Loop
If totalMiles <> 0 Then
totalResultsLabel.Text = "Total miles driven: " & totalMiles & vbCrLf &
"Total gallons used: " & totalGallons & vbCrLf & "Total MPG: " &
String.Format("{0:F}", totalMiles/totalGallons)
End If
End Sub
End Class
在此先感謝您提供的任何幫助。
太好了,謝謝。我會試一試。 – CRunge
代碼在哪裏?請原諒我的無知,我只學了兩個星期的VB。再次感謝。 – CRunge