我遇到了我的代码问题。我试图验证用户输入,所以只有数值而不是0,另一个条件是,dblFatInGrams不能大于dblCaloriesInFood。当我将这个语句添加到我的代码中时,它会直接执行else语句而不执行其余的代码。Visual Basic IF语句
Public Class Form1
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles btnCalculate.Click
Const intCaloriesPerGramoOfFat As Integer = 9 '9 calories per gram of fat
Const dblLowFoodPercent As Double = 0.3 'low fat food are less then 30 %
Dim dblCaloriesInFood As Double
Dim dblFatInGrams As Double
Dim intFatCalories As Integer
Dim dblTotal As Double
' Validating user input and show message in lable box
If (Double.TryParse(txtFoodCalories.Text, dblLowFoodPercent) And IsNumeric(txtFoodCalories.Text) And dblLowFoodPercent >= 0) Then
If (Double.TryParse(txtFatGrams.Text, dblLowFoodPercent) And IsNumeric(txtFatGrams.Text) And dblLowFoodPercent >= 0) And dblCaloriesInFood < dblFatInGrams Then
' User input
dblCaloriesInFood = CDbl(txtFoodCalories.Text)
dblFatInGrams = CDbl(txtFatGrams.Text)
'Calculate fat
intFatCalories = dblFatInGrams * intCaloriesPerGramoOfFat
' Calculate and dispaly % of cal. from fat
dblTotal = intFatCalories/dblCaloriesInFood
' Dispaly results
' Check if fat percentage is grater or equal to 30% and prints out results
If dblTotal <= dblLowFoodPercent Then
lblUserMessage.Text = "Low fat food"
lblTotal.Text = dblTotal.ToString("P")
Else
lblUserMessage.Text = "High fat food"
lblTotal.Text = dblTotal.ToString("P")
End If
Else
lblUserMessage.Text = "Enter a number of fat. Not grater than number of the calories and greater than 0"
End If
Else
lblUserMessage.Text = "Enter the number of calories. Greater than 0 "
End If
End Sub
我怀疑,编译器将保证评估从左到右。所以变量dblLowFoodPercent在你需要之前不会被TryParse填充。尝试使用“AndAlso”而不是“and”可能会使它工作,但它不是一个好的解决方案。总之,在你需要TryParse的值之前调用TryParse。我对这个结果非常感兴趣。 –
问题在于''Double.TryParse()'语句正在'dblLowFoodPercent'上运行。这可能不是你想要的。 – Icemanind
检查你的'TryParse'语句,它们都解析到同一个变量'dblLowFoodPercent'中。另外,把正确的标记,这是VB.net不是VBA。 –