计算从银行帐户中提款的次数

时间:2018-11-26 20:53:37

标签: vb.net

我正在尝试使其能够计算用户在银行帐户余额低于0之前可以进行的提款次数。输入的数字分别为1000、60、50、300、800、53、2009和2015 。应该以1000开头,然后减去60,然后是50,然后是300,然后是800,这将是4次提款。我不这样做,我也不知道我在做什么错。

Private Sub btnBankAccount_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBankAccount.Click
    Dim inFile As StreamReader = New StreamReader("bank1.txt")
    Dim withdrawls As Integer 'count times
    Dim money As Integer 'amount of money
    Dim difference As Integer = 0 'difference caused by the withdrawls


    Do 'read in numbers
        money = Val(inFile.ReadLine())
        'determine the amount of money
        If money > 0 Then
            withdrawls = withdrawls + 1
            difference = difference - money
        End If
    Loop Until difference < 0
    'display results
    Me.lblOutput.Text = withdrawls
End Sub

1 个答案:

答案 0 :(得分:0)

在我看来,如果您将difference定义为:

Dim difference As Integer = 0

现在,为了帮助您提高编码风格,建议您像这样编写代码:

Private Sub btnBankAccount_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBankAccount.Click
    Me.lblOutput.Text = GetWithdrawlCount(1000, "bank1.txt")
End Sub

Private Function GetWithdrawlCount(ByVal limit As Decimal, ByVal file As String) As Integer

    Dim withdrawls As Integer = 0
    Dim difference As Decimal = limit

    For Each line In System.IO.File.ReadLines(file)
        Dim money = Decimal.Parse(line)
        If money > 0 Then
            withdrawls = withdrawls + 1
            difference = difference - money
        End If
        If difference < 0 Then
            Exit For
        End If
    Next

    Return withdrawls

End Function

我故意将GetWithdrawlCount分隔开,以便没有没有对任何UI元素的引用,并且没有魔术数字魔术字符串。以这种方式编写代码可以使您的代码更简洁,更易于测试。