在小费计算器中使用函数

时间:2015-11-15 22:57:39

标签: vb.net

我必须为我的作业使用一个函数,但我不确定它应该如何。这就是我现在所拥有的......帮助写出函数在vb中声明的行说错了。

Dim BillTotal, TipAmount, PerPerson, TipDecimal, Total As Double
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click



    MsgBox("Tip Amount: " & TipAmount & Chr(13) & "Per Person: " & PerPerson & Chr(13) & "Total: " & Total & Chr(13))

End Sub


Function Total(ByVal BillTotal As Double) As Double
    BillTotal = mtbBill.Text
    TipAmount = (mtbTip.Text / 100) * BillTotal
    TipDecimal = (mtbTip.Text / 100)
    PerPerson = ((BillTotal * (1 + TipDecimal)) / mtbSharedBy.Text)
    Total = BillTotal * (1 + TipDecimal)
End Function

1 个答案:

答案 0 :(得分:1)

  1. 用vbNewLine替换Chr(13) - 更具可读性
  2. 添加了String.Format以更好地格式化MessageBox中的文本。 使其更具可读性
  3. 修改了您的Total函数以不接受任何参数,因为它的返回值只是从UI元素计算值


  4. Dim BillTotal,TipAmount,PerPerson,TipDecimal,Total As Double

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    
    End Sub
    
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    
    
    MsgBox(String.Format("Tip Amount: {0}{1} per person{2}{1} Total:{3}{1}", TipAmount, vbNewLine, PerPerson,Total()))
        ' Here I replaced the code with String.Format making it easier to read.
        ' You specify {0}, {1}, {2}, {n} where the number is the order of the parameter.
        ' Then at the end of your string you specify the parameter name such as TipAmount, vbNewLine(which is essentially Chr(13), PerPerson, and Total
    
    End Sub
    
    
    Function Total() As Double ' Removed the parameter passed into the function as it's not required. 
        BillTotal = mtbBill.Text
        TipAmount = (mtbTip.Text / 100) * BillTotal
        TipDecimal = (mtbTip.Text / 100)
        PerPerson = ((BillTotal * (1 + TipDecimal)) / mtbSharedBy.Text)
        Return( BillTotal * (1 + TipDecimal))
    End Function