首页 > 解决方案 > 在 ASP.NET 中使用按钮进行计算

问题描述

我正在尝试做一个超级简单的界面,用户可以在其中输入他们的本金金额、年利率和贷款期限。每月付款、付款总额、支付利息总额的计算字段。我正在计算,但不断出现错误,并且似乎小数位在整个计算过程中没有被保留?

Protected Sub btncalculate_Click(sender As Object, e As EventArgs) Handles btncalculate.Click
    Dim n As Integer
    Dim P As Integer
    Dim yr As Integer
    Dim ra As Integer
    Dim r As Integer

    n = CInt(txtmonths.Text)
    P = CInt(txtprinciple.Text)
    yr = CInt(txtyearlypercent.Text)

    ra = (yr / 100) / 12

    r = (P * ra) / (1 - (1 / (1 + ra) ^ n))

    lblmonpayments.Text = r.ToString("c")

End Sub

标签: asp.net

解决方案


我怀疑错误信息是Arithmetic operation resulted in an overflow

您收到此错误的原因是因为rar都被分配为Integer. 但是,这些用于使用除法的计算。结果很可能会返回十进制数而不是整数。只需更改要使用的变量Decimal

Protected Sub btncalculate_Click(sender As Object, e As EventArgs) Handles btncalculate.Click
    Dim n As Integer
    Dim P As Integer
    Dim yr As Integer
    Dim ra As Decimal
    Dim r As Decimal

    n = CInt(txtmonths.Text)
    P = CInt(txtprinciple.Text)
    yr = CInt(txtyearlypercent.Text)

    ra = (yr / 100) / 12

    r = (P * ra) / (1 - (1 / (1 + ra) ^ n))

    lblmonpayments.Text = r.ToString("c")

End Sub

推荐阅读