2014-09-30 69 views
1

我希望有人能澄清我在這裏做錯了什麼。我正在試圖製作一個帶有2個標籤的表單 - 攝氏和華氏兩個相應的值和1按鈕的教科書 - 轉換爲顯示攝氏度轉換爲華氏度。下面的代碼使我陷入嚴格的選項錯誤中,2代表Option Strict On禁止從'Object'到'String'的隱式轉換,2代表Option Strict On禁止從'String'到'Double'的隱式轉換。我似乎無法找到取悅嚴格選項的方法。VB上的攝氏溫度轉換器遇到嚴格的選項錯誤

Private Sub btnConvert_Click(sender As Object, e As EventArgs) Handles btnConvert.Click 
    Dim celsius As String 
    Dim answer As String 
    Dim fahrenheit As String 

    celsius = txtCelsius.Text 
    fahrenheit = txtFahrenheit.Text 

    If String.IsNullOrEmpty(txtFahrenheit.Text) Then 
     answer = celsius * 9/5 + 32 
     txtFahrenheit.Text = Int(answer) 
    End If 
    If String.IsNullOrEmpty(txtCelsius.Text) Then 
     answer = (fahrenheit - 32) * 5/9 
     txtCelsius.Text = Int(answer) 
+0

提示:您的攝氏,華氏和答案變量應該是數字類型,而不是字符串。這會讓你的錯誤更容易解決 – 2014-09-30 08:34:49

回答

0

隨着選項嚴格在

你需要自己做轉換

我編輯了自己的代碼,試試這個

 Dim celsius As String 
     Dim answer As String 
     Dim fahrenheit As String 

     celsius = txtCelsius.Text 
     fahrenheit = txtFahrenheit.Text 

     If String.IsNullOrEmpty(txtFahrenheit.Text) Then 
      answer = CStr(CDbl(celsius) * 9/5 + 32) 
      txtFahrenheit.Text = answer 
     End If 
     If String.IsNullOrEmpty(txtCelsius.Text) Then 
      answer = CStr((CDbl(fahrenheit) - 32) * 5/9) 
      txtCelsius.Text = answer 
     End If 
0

您有可以固定/作出了明確許多隱式轉換:

你必須在celsius * 9/5 + 32(fahrenheit - 32) * 5/9隱式轉換。 celciusfarhenheit是字符串,但是您將其用作數字。

當你把結果到答案您還可以: answer = celsius * 9/5 + 32
answer是一個字符串,但你要指定一個計算的結果。它應該是一個雙重或類似的數據類型,而不是一個字符串。

然後當你把Int(answer)放到一個文本框中。 第一個answer仍然是一個字符串,但如果我記得的話,Int()需要一個數字(雙)。然後你把這個結果,並把自動轉換爲字符串: txtCelsius.Text = Int(answer)

相關問題