vb.net - 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
解决方案
您的(意思是 kushlord420)解决方案存在一些问题。
- Visual Basic 代码不区分大小写,因此 bmi 与 BMI 相同
- 你永远不会使用表单级别的变量 bmi 所以删除。
- 您尝试编写自定义构造函数,但在 vb.net 中它是 Sub New
- 您正在将重量和高度文本框中的值转换为 Double,但您的属性是 Single 类型。实际上这应该是 Single.TryParse 但那是另一天。
- vb.net 中的函数必须具有返回值的数据类型。这在函数的第一行中提供。由于您在返回值上使用了格式,因此我将值设为字符串并转换了返回值。
- 修复了构造函数参数以避免歧义。
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
推荐阅读
- c++ - DirectX 11 渲染到特定区域
- multithreading - 为什么 xsub 中的静态变量不是线程安全的?
- vba - VBA自动化无法获取innerText(innerHTML,值)
- java - @JoinColumn 注释中的 name 和 referencedColumnName 之间的区别?
- sql - 简单的正则表达式过滤掉前后字符
- android - 使用返回堆栈中的片段刷新活动
- c# - AngularJS 100 以上记录未加载
- javascript - 将输入发送到 Ajax 中的文件
- bayesian - 使用 stan_glmer 进行 beta 回归的 rstanarm 错误
- vb.net - Visual Basic 中的扩展十六进制地址