VB - 负数和条件语句

时间:2015-02-03 17:47:27

标签: vb.net

再次回到另一个noob问题,这个问题正在惹恼我。我花了两天时间试图把这一个拿出来。似乎我和VB以及负数总是有误解。

我在程序中得到了一个胖百分比计算器的所有其他工作,除了条件语句,如果两个文本框字符串的双重转换小于零,应该打印出错误消息。但是,即使我在测试时输入两个负数,程序也会跳过我的Else错误语句并计算两个负数,并获得一些完全荒谬的胖百分比数字。如果" If-Then"它看起来好像只是用表达式来表达它。我做数学的部分代码和百分比答案不匹配。

Private Sub btnCalculate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnCalculate.Click

    'Declare variables
    Dim dblCaloriesInFood As Double
    Dim dblGramsOfFat As Double
    Dim dblPercentageOfCaloriesFromFat As Double
    Dim dblCaloriesFromFat As Double


    'Always initialize lblLowInFat message as not visible when button is clicked
    lblLowInFat.Visible = False

    Try
        'Converting textbox strings to double. 

        dblCaloriesInFood = CDbl(txtCaloriesInFood.Text)
        dblGramsOfFat = CDbl(txtGramsOfFat.Text)

        If dblCaloriesInFood Or dblGramsOfFat > 0 Then

            'Calculate Calories from fat
            dblCaloriesFromFat = dblGramsOfFat * 9

            'Calculate percentage of calories from fat
            dblPercentageOfCaloriesFromFat = dblCaloriesFromFat / dblCaloriesInFood

            'Display percentage of calories from fat
            If dblPercentageOfCaloriesFromFat >= 0 Then
                lblMessage.Text = dblPercentageOfCaloriesFromFat.ToString("p")
            Else
                lblMessage.Text = String.Empty
            End If

            'Display low fat message
            If dblPercentageOfCaloriesFromFat <= 0.3 And dblPercentageOfCaloriesFromFat > 0 Then
                lblLowInFat.Visible = True
            End If
        Else
            'really tried to make this message work but couldn't figure it out.
            'why does it only display this message when zero is entered and not when
            'negative numbers are entered. instead it just calculates the negative numbers
            'as if they were whole positive numbers or something, not sure because the percentage
            'is way off the charts when i enter negative numbers. can't figure this out.
           MessageBox.Show("Either the calories or fat grams were incorrectly entered")
            txtCaloriesInFood.Text = String.Empty
            txtGramsOfFat.Text = STring.Empty
            txtCaloriesInFood.Focus()

        End If

    Catch
        'error message for invalid input
        MessageBox.Show("Please enter a numeric value for calories in food & number of fat grams.")
        txtCaloriesInFood.Focus()
    End Try



End Sub

1 个答案:

答案 0 :(得分:4)

您的If声明错误。首先,您需要分别测试这两个值。其次,您希望两个值都大于零,因此您应该使用And而不是Or(这意味着只有一个必须大于零)。

If dblCaloriesInFood > 0 And dblGramsOfFat > 0 Then