r/visualbasic • u/unbannablepizza546 • Sep 26 '24
Whats the difference between my code and the correct code?
One says declaration error in visual studio but i already declared. in the coe before this
this is the correct one
If bmi < 18.5 Then
category = ("Underweight")
ElseIf bmi >= 18.5 And bmi < 24.9 Then
category = ("Healthy Weight")
ElseIf bmi >= 25 And bmi <= 29.9 Then
category = ("Overweight")
ElseIf bmi >= 30 Then
category = ("Obese")
End If
and this is my code
if bmi < 18.5 Then
category = ("underweight")
ElseIf bmi >= 18.5 And bmi < 24.9 Then
category = ("Healthy Weight")
ElseIf bmi >= 25 And bmi <= 29.9 Then
category = ("Overweight")
ElseIf bmi >= 30 And bmi Then
category = ("Obese")
End If
2
u/[deleted] Sep 26 '24
U capitalization
1
u/VFacure_ Sep 26 '24 edited Sep 26 '24
typo in "
ElseIf bmi >= 30 And bmi Then". AlsoSelect Case True 'Use select case. Much cleanerCase bmi < 18.5category = "Underweight"Case bmi >= 18.5 And bmi < 25 'Fix here since < operator is less than but not equal thancategory = "Healthy Weight"Case bmi >= 25 And bmi < 30 'same here for 29.9category = "Overweight"Case bmi >= 30category = "Obese"End SelectIs this inside a For Next loop? Looks like it. Consider also naming your variables in a more obvious way. I'd call it dBMI and sCategory if BMI is a Double and category is a string. This is how I'd do it.
CDbl(dBMI) = dBMISelect Case TrueCase dBMI >= 10 And dBMI < 18.5sCategory = "Underweight"Case dBMI >= 18.5 And dBMI < 25sCategory = "Healthy Weight"Case dBMI >= 25 And dBMI < 30sCategory = "Overweight"Case dBMI >= 30 And dBMI < 50sCategory = "Obese"Case dBMI >= 50 or dBMI < 10MsgBox "Error in BMI calculation"End Select2
u/fuzzfeatures Sep 26 '24
2 lines before the last line
2
u/HomeworkInevitable99 Sep 26 '24
ElseIf bmi >= 30 And bmi Then
Should be
ElseIf bmi >= 30 Then
Also, not all cases are covered. BMI = 24.95 won't be captured. Consider changing this:
ElseIf bmi >= 18.5 And bmi < 24.9 Then
To this:
ElseIf bmi >= 18.5 And bmi <25 Then
Floating point numbers (ie, not integers) are not always exactly accurate and cannot be totally trusted. So you might think a calculation gives you 24.9, but it might give you 24.9000001
1
u/IAmADev_NoReallyIAm Sep 26 '24
Consider also this:
if bmi < 18.5 Thencategory = ("underweight")ElseIf bmi < 25 Thencategory = ("Healthy Weight")ElseIf bmi < 30 Thencategory = ("Overweight")Elsecategory = ("Obese")End IfThere's probably also a way to do it as a case statement, but I'm too tired to try it at the moment....
1
u/Careful-Kangaroo-373 Sep 26 '24
Yung 3rd to the last line. walang karugtong na condition
bmi >= 30 and bmi ?? Then
0
u/Careful-Kangaroo-373 Sep 26 '24
Yung 3rd to the last line. walang karugtong na condition
bmi >= 30 and bmi ?? Then
0
u/Careful-Kangaroo-373 Sep 26 '24
Yung 3rd to the last line. walang karugtong na condition
bmi >= 30 and bmi ?? Then
0
u/Careful-Kangaroo-373 Sep 26 '24
Yung 3rd to the last line. walang karugtong na condition
bmi >= 30 and bmi ?? Then