首页 > 解决方案 > 我希望代码输出从第 1 年到第 5 年的每个贬值的年份,目前它只为所有 5 个值显示 1

问题描述

下面的代码每年显示“1”,应该是“1”到“5”

Public Class Form1
    Private Sub btnDisplay_Click(sender As Object, e As EventArgs) Handles btnDisplay.Click

        Dim cost As Double
        Dim life As Double = CDbl(ListBox1.SelectedItem)
        Dim salvage As Double
        Dim numberperiod As Integer
        Dim period As Integer
        Dim depreciation1 As Double
        Dim depreciation2 As Double
        Dim isconverted1 As Boolean
        Dim isconverted2 As Boolean
        Dim isconverted3 As Boolean
        Dim year As Integer = 0

        isconverted1 = Double.TryParse(textbox1.Text, cost)
        isconverted2 = Double.TryParse(textbox2.Text, salvage)
        isconverted3 = Integer.TryParse(ListBox1.SelectedItem, period)

        lstDCB.Items.Add("Year        Depreciation")
        lstSOTY.Items.Add("Year        Depreciation")

        year = Val(year) + 1

        For numberperiod = 1 To period Step 1
            depreciation1 = Financial.DDB(cost, salvage, life, numberperiod)
            depreciation2 = Financial.SYD(cost, salvage, life, numberperiod)

            lstDCB.Items.Add(year & "              " & Math.Round(depreciation1, 2, MidpointRounding.AwayFromZero))
            lstSOTY.Items.Add(year & "              " & Math.Round(depreciation2, 2, MidpointRounding.AwayFromZero))

        Next numberperiod

    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        Me.Close()
    End Sub
End Class

它应该在 DDB 和 SYD 的年份下显示 1 到 5。

标签: vb.netvisual-studio

解决方案


如果您查看您发布的代码,您将永远不会更新year例程中的变量,因为它被初始化为零,然后使用语句进行更新year = Val(year) + 1

我相信您的意思是将该语句放在循环体中(在计算之后),以便它在循环的每次迭代中递增。

像这样的东西:

Module VBModule

    Sub Main()
        Dim cost As Double = 100
        Dim life As Double = 12
        Dim salvage As Double = 3
        Dim numberperiod As Integer
        Dim period As Integer = 3
        Dim depreciation1 As Double
        Dim depreciation2 As Double
        Dim year As Integer = 0

        For numberperiod = 1 To period Step 1
            depreciation1 = Financial.DDB(cost, salvage, life, numberperiod)
            depreciation2 = Financial.SYD(cost, salvage, life, numberperiod)

            Console.WriteLine(year & " " & Math.Round(depreciation1, 2, MidpointRounding.AwayFromZero))
            Console.WriteLine(year & " " & Math.Round(depreciation2, 2, MidpointRounding.AwayFromZero))

            year += 1
        Next numberperiod
    End Sub

End Module

推荐阅读