2017-03-23 27 views
-1

我正在嘗試製作一個簡單的BMI應用,並且我試圖獲得它,所以當你輸入你的體重和身高時,它會做數學。創建一個BMI應用

當然我得到

這裏的漁獲「從‘字符串’到‘雙’隱式轉換」:它把它給我,當我試圖將字符串轉換爲文本;但是現在當我在該行上只有Option Strict時,它給了我第1行的錯誤。

所以我想知道如何去使用正確的算法來解決這個問題?我剛開始使用VB.net,現在只是無法理解我在做什麼。

我看了另一篇文章,奇怪的是我仍然試圖找出它,因爲我還沒有了解Double.TryParse()。

下面的代碼:

 Dim strbmi As String 
    Dim strHeight As String 
    Dim strweight As String 
    Dim decbmi As Decimal 


    strweight = txtWeight.Text 
    strHeight = txtHeight.Text 
    strbmi = lblBMI.Text 

    If IsNumeric(txtHeight) Then 
     strHeight = Convert.ToString(txtHeight.Text) 
    End If 
    If IsNumeric(txtHeight) Then 
     strHeight = Convert.ToString(txtHeight.Text) 
    End If 
    If IsNumeric(txtWeight) Then 
     strweight = Convert.ToString(txtWeight.Text) 
    End If 

    If decbmi <= 18.5 Then 
     lblBMICategory.Text = "Underweight" 
    ElseIf decbmi <= 25 Then 
     lblBMICategory.Text = "Normal Weight" 

    ElseIf decbmi <= 30 Then 
     lblBMICategory.Text = "Overweight" 
    ElseIf decbmi > 30 Then 
     lblBMICategory.Text = "Obesity" 
    End If 
+1

可能重複[Convert String to Double - VB](http://stackoverflow.com/questions/1172306/convert-string-to-double-vb) – dave

回答

0

好吧,我相信你誤以爲一些概念。對於所有的實際效果,字符串文本。你必須先將它轉換爲數字(並捕捉並處理你可能會遇到的錯誤),然後再進行數學運算。這是我認爲你應該做的:

Function BMI(strHeight As String, strweight As String) As String 
    Dim dblHeight, dblWeight As Double 
    If Not Double.TryParse(strHeight, dblHeight) Then Return "Invalid Entry: Height" 
    If Not Double.TryParse(strweight, dblWeight) Then Return "Invalid Entry: Weight" 
    Dim dblBMI = dblWeight/(dblHeight^2) 
    If dblBMI <= 18.5 Then 
     Return "Underweight" 
    ElseIf dblBMI <= 25 Then 
     Return "Normal Weight" 
    ElseIf dblBMI <= 30 Then 
     Return "Overweight" 
    Else 
     Return "Obesity" 
    End If 
End Function