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
解决方案
在我看来,如果您这样定义,您的代码应该可以工作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 元素的引用,并且代码中没有幻数或幻字符串。以这种方式编写它可以使您的代码更清晰,更易于测试。
推荐阅读
- r - 使用 ends_with 在 R 中动态选择列
- php - 使用一个php文件在两个具有关系(PK,FK“user_id”)的表中插入数据
- selenium - 无法识别以下代码的元素
- angular6 - 如何为表单验证生成错误消息
- google-colaboratory - 访问 Google Colab 中 /contents 文件夹的内容?
- mysql - 错误:无法为数据库引擎 MYSQL 加载 /usr/local/lib64/kamailio//kamctl/kamdbctl.mysql 中的脚本
- excel - 使用互操作访问 Excel 中的名称时出错
- ios - 项目错误:此 mkspec 需要 Xcode 4.3 或更高版本
- java - 如何在代码中表示上下文无关语法?
- android - 如何使用 Dagger 为构造函数注入提供自定义依赖项