首页 > 解决方案 > 计算从银行账户取款的次数

问题描述

我正在尝试让它计算在银行账户余额低于 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

标签: vb.net

解决方案


在我看来,如果您这样定义,您的代码应该可以工作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 元素的引用,并且代码中没有幻数幻字符串。以这种方式编写它可以使您的代码更清晰,更易于测试。


推荐阅读