首页 > 解决方案 > Visual Basic BMI Calculator gives NaN result

问题描述

I'm doing an IT course for college and one of the assignments requires you to create a BMI calculator in Visual Basic with the use of object orientated techniques. I'm not a very good programmer and thus I'm stuck on a problem I keep receiving. The code I'm using was given to me by someone who claimed it works, however when I run the program any results given are NaN.

Anyone have an idea as to what is wrong with the code in order to give me this result?

Here is the code I'm using:

Public Class Form1
Private Sub Button_Calculate_Click(sender As Object, e As EventArgs) Handles 
Button_Calculate.Click
    Dim height As Double = Double.Parse(TextBox_Height.Text)
    Dim weight As Double = Double.Parse(TextBox_Weight.Text)


    bmi.SetWeight(weight)
    bmi.SetHeight(height)

    TextBox_BMI.Text = Format(bmi.GetBMI(), "0.00")
End Sub

Private bmi As New BMI
End Class

In a separate class:

Public Class BMI
Public Function GetBMI()
    Return (weight / (height ^ 2))
End Function

Public Function GetWeight()
    Return weight
End Function
Public Function GetHeight()
    Return height
End Function

Public Function SetWeight(_weight As Double)
    Return weight = _weight
End Function
Public Function SetHeight(_height As Double)
    Return height = _height
End Function

Private weight As Double
Private height As Double
End Class

标签: vb.netcalculator

解决方案


您的(意思是 kushlord420)解决方案存在一些问题。

  1. Visual Basic 代码不区分大小写,因此 bmi 与 BMI 相同
  2. 你永远不会使用表单级别的变量 bmi 所以删除。
  3. 您尝试编写自定义构造函数,但在 vb.net 中它是 Sub New
  4. 您正在将重量和高度文本框中的值转换为 Double,但您的属性是 Single 类型。实际上这应该是 Single.TryParse 但那是另一天。
  5. vb.net 中的函数必须具有返回值的数据类型。这在函数的第一行中提供。由于您在返回值上使用了格式,因此我将值设为字符串并转换了返回值。
  6. 修复了构造函数参数以避免歧义。
    Sub Button_Calculate_Click(sender As Object, e As EventArgs) Handles Button_Calculate.Click
        Dim bmi As New BMI(CSng(TextBox_Weight.Text), CSng(TextBox_Height.Text))
        TextBox_BMI.Text = Format(bmi.GetBMI(), "0.00")
    End Sub

    Public Class BMI
        Public Function GetBMI() As String
            Return (Weight / (Height ^ 2)).ToString
        End Function

        Public Property Weight As Single
        Public Property Height As Single

        Public Sub New(wght As Single, hght As Single)
            Weight = wght
            Height = hght
        End Sub
    End Class

推荐阅读