我得到了另一个超级基本问题,我试图总计用户输入的txtPrice.Text中每个条目的小计,然后使用更新的税,运费和总计刷新其他标签。它不总是subTotal,其他一切正常。那是怎么回事?
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
Dim sglSub As Single
Dim sglTotal As Single
Dim sglSalesTax As Single
Const TAX_RATE As Single = 0.02
Dim bytShippingCharge As SByte = 10
Dim sglCompTotal As Single
Single.TryParse(txtPrice.Text, sglSub)
sglTotal += sglSub
lblSubTotal.Text = sglTotal.ToString("C2")
sglSalesTax = (sglTotal * TAX_RATE)
lblTax.Text = sglSalesTax.ToString("C2")
If sglTotal >= 100 Then
bytShippingCharge = 0
End If
lblShipping.Text = bytShippingCharge.ToString("C2")
sglCompTotal = (sglTotal + sglSalesTax + bytShippingCharge)
lblTotal.Text = sglCompTotal.ToString("C2")
End Sub
答案 0 :(得分:1)
提示 在这一行:
sglTotal += sglSub
- 每次使用总计时,在向其添加值之前将其初始化为零。否则会导致不良后果。
- 使用货币时最好使用小数类型。
如果你想让变量保持其值,则声明它是共享的。
这是一个如何使用共享字段的小例子
Public Class Form1
Shared total As Decimal = 0D
Shared Sub calc()
total += 2
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
calc()
Label1.Text = total.ToString
End Sub
End Class