我很难弄清楚我的BMI计算器出了什么问题。当我进入体重指数小于10时,他们会显示为肥胖。如果我输入10以上的任何东西,它会显示为体重不足。任何帮助将不胜感激。
这张照片是我的问题的一个例子:
以下是我的计算代码:
Protected Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
Dim bmi As Double
Dim bmiRounded As Double
bmi = (txtWeight.Text * 703) / (txtHeight.Text * txtHeight.Text)
bmiRounded = Math.Round(bmi, 1)
lblBMI.Text = bmiRounded
Select Case lblBMI.Text
Case 0.0 To 18.5
lblBMIResult.Text = "Underweight"
Case 18.6 To 24.9
lblBMIResult.Text = "Normal"
Case 25.0 To 29.9
lblBMIResult.Text = "Overweight"
Case Is >= 30.0
lblBMIResult.Text = "Obese"
End Select
End Sub
答案 0 :(得分:0)
您的代码存在一些问题:
txtWeight.Text
和txtHeight.Text
中的值转换为数字,而不是依靠编译器为您隐式转换它们。height ^ 2
。bmiRounded
代替lblBMI.Text
中的Select Case
。Case Is <= 18.5
,就像你对最后一种情况所做的那样。以下是包含以上所有建议的更新版本:
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
Dim bmi As Double
Dim bmiRounded As Double
Dim height As Integer = Integer.Parse(txtHeight.Text)
Dim weight As Integer = Integer.Parse(txtWeight.Text)
bmi = (weight * 703) / (height ^ 2)
bmiRounded = Math.Round(bmi, 1)
lblBMI.Text = bmiRounded
Select Case bmiRounded
Case Is <= 18.5
lblBMIResult.Text = "Underweight"
Case 18.6 To 24.9
lblBMIResult.Text = "Normal"
Case 25.0 To 29.9
lblBMIResult.Text = "Overweight"
Case Is >= 30.0
lblBMIResult.Text = "Obese"
End Select
End Sub
注意:我假设您将以整数形式输入身高和体重,但如果您想以小数点输入它们,请转换为Double
而不是Integer
:
Dim height As Double = Double.Parse(txtHeight.Text)
Dim weight As Double = Double.Parse(txtWeight.Text)
答案 1 :(得分:0)
对数字使用数字变量。不要使用字符串参数尝试数学。将Option Strict On
放在代码文件的顶部。
Option Strict On
Public Class Form1
Private Sub btnCalc_Click(sender As Object, e As EventArgs) Handles btnCalc.Click
Dim height As Double = Double.Parse(txtHeight.Text)
Dim weight As Double = Double.Parse(txtWeight.Text)
Dim bmi As Double = (weight * 703) / (height * height)
Dim bmiRounded As Double = Math.Round(bmi, 1)
lblBMI.Text = bmiRounded.ToString()
Select Case bmiRounded
Case 0.0 To 18.5
lblBMIResult.Text = "Underweight"
Case 18.6 To 24.9
lblBMIResult.Text = "Normal"
Case 25.0 To 29.9
lblBMIResult.Text = "Overweight"
Case Is >= 30.0
lblBMIResult.Text = "Obese"
End Select
End Sub
End Class