这是我第一次在这里发帖。对于我正在上课的课程,我遇到了一些困难。我需要获得里程和加仑然后计算每个条目的MPG。我有这个部分想通了。我似乎无法得到的是底部的总数。我需要在每个ListBox中添加所有项目的总和,并在每次单击按钮时计算总MPG。到目前为止,这是我的代码。
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
提前感谢您提供的任何帮助。
答案 0 :(得分:3)
由于您要将while
与总和进行比较,因此ListBox.Items.Count
循环条件不正确。我会使用Linq
代替,因为它更具可读性:
Dim totalMiles As Int32 = milesListBox.Items.Cast(Of Int32)().Sum()
Dim totalGallons As Int32 = gallonsListBox.Items.Cast(Of Int32)().Sum()