90 likes | 239 Vues
This program efficiently handles an unknown number of sales input values through a loop, allowing users to enter values until an empty string is provided. It accumulates the total sales and counts the number of entries, enabling the calculation of the average sales amount. The implementation is demonstrated in two versions of a button click event, showcasing how to gather user input via InputBox, process the values, and display the average or a message indicating no sales. This method exemplifies the use of repetition structures in programming.
E N D
Repetition Structures Yonglei Tao
Counting and Accumulating • Write a program to process input, the number of input values are unknown • Sample input • 27.50 55.00 38.74 88.26 <empty string> • 27.50 63.98 55.00 96.11 38.74 88.26 <empty string> • <empty string>
Loop Design • Get a value • If it is not the empty string • Process the value • Get a value • If it is not the empty string • Process the value • Get a value • If it is not the empty string • Process the value • Get a value • … • If it is the empty string • Done Get a value Do While it’s not an empty string Process the value Get a value Loop
Program Version One Private Sub btnCalculate_Click ( … ) Dim sales As String Dim numSales As Integer sales = InputBox (“Enter a sales amount. Click Cancel to end.“, “Sales Entry”) Do While sales <> String.Empty ‘ process the value sales = InputBox (“Enter a sales amount. Click Cancel to end.“, “Sales Entry”) Loop ‘ display the average End Sub
Program Version Two Private Sub btnCalculate_Click ( … ) Dim sales As String Dim numSales As Integer Dim totalSales, avgSales As Currency sales = InputBox (“Enter a sales amount. Click Cancel to end.“, “Sales Entry”) Do While sales <> String.Empty ‘ process the value numSales = numSales + 1 totalSales = totalSales + Val (sales) sales = InputBox (“Enter a sales amount. Click Cancel to end.“, “Sales Entry”) Loop ‘ display the average End Sub
Private Sub btnCalculate_Click ( … ) Dim sales As String Dim numSales As Integer Dim totalSales, avgSales As Currency sales = InputBox (“Enter a sales amount. Click Cancel to end.“, “Sales Entry”) Do While sales <> String.Empty numSales = numSales + 1 totalSales = totalSales + Val (sales) sales = InputBox (“Enter a sales amount. Click Cancel to end.“, “Sales Entry”) Loop If ( numSales > 0 ) Then avgSales = totalSales / numSales lblAerage.Text = Format ( avgSales. “Currency”) else lblAerage.Text = “No Sales” end If End Sub