函数始终返回0值

时间:2015-12-22 15:42:07

标签: vb.net

    Dim price, dprice, total As Double

    total = price + dprice

    lstOutput.Items.Add("Cheese Cake : $ " & (FormatNumber(price, 2)))
    lstOutput.Items.Add("Drink : $ " & (FormatNumber(dprice, 2)))
    lstOutput.Items.Add("===================")
    lstOutput.Items.Add("Total : " & (FormatNumber(total, 2)))

End Sub

Function GetCakePrice(price As Double) As Double

    If chkChoco.Checked Then
        price += 2.0
    End If
    If chkBerry.Checked Then
        price += 2.5
    End If
    If chkBlack.Checked Then
        price += 3.0
    End If
    GetCakePrice = price
End Function

Function GetDrinkPrice(dprice As Double) As Double
    If radTea.Checked Then
        dprice += 1.8
    End If
    If radCoffee.Checked Then
        dprice += 2.0
    End If
    GetDrinkPrice = dprice
End Function

现在显示屏显示芝士蛋糕和饮料:尽管已经勾选了复选框,但仍然是0美元。试着修修补补,请指出我的错误。

2 个答案:

答案 0 :(得分:0)

您正在打印的变量未在任何位置设置。要填写它们,你需要这样的东西: -

price = GetCakePrice()  ' (The passed parameter serves no purpose here)

并且函数中的第一行声明了一个本地工作变量: -

Function GetCakePrice() As Double

    Dim price As Double

    If chkChoco.Checked Then
    .
    .
    etc
    .

答案 1 :(得分:0)

您缺少调用您声明的函数,并向它们发送您不需要的参数。我建议您更改代码如下:

注意:我假设代码的第一部分是另一种方法,所以我只称它为Method()。

Sub Method()
    Dim price, dprice, total As Double

    price = GetCakePrice()
    dprice = GetDrinkPrice()

    total = price + dprice

    lstOutput.Items.Add("Cheese Cake : $ " & (FormatNumber(price, 2)))
    lstOutput.Items.Add("Drink : $ " & (FormatNumber(dprice, 2)))
    lstOutput.Items.Add("===================")
    lstOutput.Items.Add("Total : " & (FormatNumber(total, 2)))
End Sub

Function GetCakePrice() As Double
    If chkChoco.Checked Then
        price += 2.0
    End If
    If chkBerry.Checked Then
        price += 2.5
    End If
    If chkBlack.Checked Then
        price += 3.0
    End If
    GetCakePrice = price
End Function

Function GetDrinkPrice() As Double
    If radTea.Checked Then
        dprice += 1.8
    End If
    If radCoffee.Checked Then
        dprice += 2.0
    End If
    GetDrinkPrice = dprice
End Function