计算美元,四分之一,硬币,镍币,便士数量便士的便士数量

时间:2018-05-18 16:29:41

标签: .net vb.net

我在VB.NET中有一个功课,我必须计算在银行兑换硬币时我将获得的美元,四分之一,硬币,镍币和便士的数量。我拥有的便士数可以是随机数。到目前为止,我的代码在这里:

Option Explicit On
Option Strict Off
Option Infer Off


Public Class frmMain
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load

End Sub

Private Sub btnExit_Click(sender As Object, e As EventArgs) Handles btnExit.Click
    Me.Close()

End Sub

Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click

    Dim intDollars As Integer
    Dim intQuarters As Integer
    Dim intDimes As Integer
    Dim intNickels As Integer
    Dim intPennies As Integer

    Integer.TryParse(txtNumPennies.Text, intDollars)
    intDollars = txtNumPennies.Text \ 100
    txtDollars.Text = Convert.ToString(intDollars)

    Integer.TryParse(txtNumPennies.Text, intQuarters)
    intQuarters = (txtNumPennies.Text - txtDollars.Text * 100) \ 25
    txtQuarters.Text = Convert.ToString(intQuarters)

    Integer.TryParse(txtNumPennies.Text, intDimes)
    intDimes = (txtNumPennies.Text Mod 25) \ 10
    txtDimes.Text = Convert.ToString(intDimes)

    Integer.TryParse(txtNumPennies.Text, intNickels)
    intNickels = (txtNumPennies.Text Mod 10) \ 5
    txtNickels.Text = Convert.ToString(intNickels)

    Integer.TryParse(txtNumPennies.Text, intPennies)
    intPennies = (txtNumPennies.Text Mod 5) \ 1
    txtPennies.Text = Convert.ToString(intPennies)

End Sub

Private Sub txtNumPennies_TextChanged(sender As Object, e As EventArgs) Handles txtNumPennies.TextChanged

    txtDollars.Text = String.Empty
    txtQuarters.Text = String.Empty
    txtDimes.Text = String.Empty
    txtNickels.Text = String.Empty
    txtPennies.Text = String.Empty

End Sub
End Class

不知何故,它不是正确的计算,特别是尼克。我很乐意感谢任何有用的提示!非常感谢你。

1 个答案:

答案 0 :(得分:1)

你没有删除已经转换过的便士数量,所以你的钱数倍增(如果现实生活那么容易!)。此外,您不断尝试转换文本而不检查它是否有效 - 而且您正在重复自己。

if Integer.TryParse(txtNumPennies.Text, numPennies) Then
    ' all your conversions go here. I am providing two examples below.
    intDollars = numPennies \ 100
    txtDollars.Text = Convert.ToString(intDollars)
    numPennies = numpennies - (intDollars * 100)

    intQuarters = numpennies \ 25
    txtQuarters.Text = Convert.ToString(intQuarters)
    numPennies = numpennies - (intQuarters * 25)
    ' ... and so on
End If

如果你遵循上面的逻辑,你会看到它反映了现实生活中发生的事情 - 首先将便士兑换成美元,转换后的便士不再存在。