我正在上大学的IT课程,其中一项任务要求您使用面向对象的技术在Visual Basic中创建一个BMI计算器。我不是一个很好的程序员,因此我一直困扰着我不断收到的问题。我使用的代码是由声称可以使用的人提供给我的,但是当我运行该程序时,给出的任何结果都是NaN。
为了给我这个结果,任何人都知道代码有什么问题吗?
这是我正在使用的代码:
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
在单独的班级:
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
答案 0 :(得分:2)
您的(意思是kushlord420)解决方案存在一些问题。
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
答案 1 :(得分:1)
您确实需要更多类似这样的东西:
Public Class BMI
Public Function GetBMI() As Double
Return (weight / (height ^ 2))
End Function
Public Property Weight As Double
Public Property Height As Double
Public Sub New(weight As Double, height As Double)
Me.Weight = weight
Me.Height = height
End Sub
End Class
Public Class Form1
Private Sub Button_Calculate_Click(sender As Object, e As EventArgs) Handles Button_Calculate.Click
Dim bmi As New BMI(CDbl(TextBox_Weight.Text), CDbl(TextBox_Height.Text))
TextBox_BMI.Text = Format(bmi.GetBMI(), "0.00")
End Sub
End Class
或者更好的是,
Public Class BMI
Public Property Weight As Double
Public Property Height As Double
Public ReadOnly Property BMI As Double
Get
Return (Weight / (Height ^ 2))
End Get
End Property
Public Sub New()
End Sub
Public Sub New(weight As Double, height As Double)
Me.Weight = weight
Me.Height = height
End Sub
End Class
答案 2 :(得分:-1)
在朋友的帮助下,找出了我的问题。
如果有人好奇,请使用以下代码:
Public Class Form1
Sub Button_Calculate_Click(sender As Object, e As EventArgs) Handles
Button_Calculate.Click
Dim bmi As New BMI With {.Weight = CDbl(TextBox_Weight.Text), .Height =
CDbl(TextBox_Height.Text)}
TextBox_BMI.Text = Format(bmi.GetBMI(), "0.00")
End Sub
Private bmi As New BMI
End Class
并且:
Public Class BMI
Public Function GetBMI()
Return (weight / (height ^ 2))
End Function
Property Weight As Single
Property Height As Single
Public Sub BMI(weight As Single, height As Single)
Me.Weight = weight
Me.Height = height
End Sub
End Class