2014-09-13 357 views
-2

我想寫一個程序在vb中要求用戶在華氏文本框或攝氏溫度文本框中鍵入一個值。我只想使用ONE按鈕來執行計算和兩個文本框來顯示輸出,但我不知道我明白髮生了什麼。我在文本框中鍵入的數字不是已經計算出來的。華氏溫度到攝氏轉換器在Visual Basic

下面的代碼:

Private Sub convertButton_Click(sender As Object, e As EventArgs) Handles convertButton.Click 

    Dim FahrenheitValue, CelsiusValue As Double 

    FahrenheitValue = Val(fahrenheitBox.Text) 
    CelsiusValue = Val(celsiusBox.Text) 

     FahrenheitValue = (9/5) * (CelsiusValue + 32) 
     CelsiusValue = (5/9) * (FahrenheitValue - 32) 

     celsiusBox.Text = CelsiusValue 
     fahrenheitBox.Text = FahrenheitValue 


End Sub 

我想我最好不要創建計算不同的按鈕。如何讓Boxes接受並計算輸入框中的正確值?

+0

輸入您的問題的標題在谷歌返回大量的使用建議。你有沒有試過這些? – lxg 2014-09-13 14:38:46

+0

是的,但他們都涉及使用表單上的多個按鈕來執行計算。 – 2014-09-13 14:45:36

+0

你需要*東西*來預測用戶的意圖2個按鈕,一個組合或單選按鈕。 – Plutonix 2014-09-13 14:51:52

回答

4

的一個主要問題是在這裏:

FahrenheitValue = (9/5) * (CelsiusValue + 32) 
CelsiusValue = (5/9) * (FahrenheitValue - 32) 

除了數學是一點點關閉你是對的再次使用它之前更改值。

I.E.我在攝氏輸入0:

  • FV =(9/5)* 0 + 32

FV現在等於32

  • CV =(5/9)* 32 - 32 == -14.22

試試這個:

 Dim ResultFV As Double = (CelsiusValue * (5/9) + 32) 
     Dim ResultCV As Double = (FahrenheitValue - 32) * (9/5) 

此外,清除文本框值後,將會很明智。

編輯

其他評論也正確的,另外一個問題是你沒有設置需要做哪些計算。

嘗試:

Public Class Form1 
    Dim celsiusActive As Boolean 


    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click 
      Dim FahrenheitValue As Double = 0 
      Dim CelsiusValue As Double = 0 

      FahrenheitValue = Val(fahrenheitBox.Text) 
      CelsiusValue = Val(celsiusBox.Text) 

      Dim ResultFV As Double = (CelsiusValue * (5/9) + 32) 
      Dim ResultCV As Double = (FahrenheitValue - 32) * (9/5) 


      If celsiusActive Then 
       fahrenheitBox.Text = ResultFV 
      Else 
       celsiusBox.Text = ResultCV 
      End If 

    End Sub 

    Private Sub celsiusBox_TextChanged(sender As Object, e As EventArgs) Handles celsiusBox.TextChanged 
      celsiusActive = True 
    End Sub 

    Private Sub fahrenheitBox_TextChanged(sender As Object, e As EventArgs) Handles fahrenheitBox.TextChanged 
      celsiusActive = False 
    End Sub 
End Class 
1

,如果我理解正確,攝氏值會如果用戶輸入的華氏文本框中的值是什麼。這樣,您的華氏溫度值將始終按(9/5)*(0 + 32)計算。如果相反,它應該可以工作。 我認爲你需要檢查用戶輸入的值,並根據這個值執行相應的計算。

的代碼將是某事像這樣:

if fahrenheitBox.Text IS Nothing then 
CelsiusValue = Val(celsiusBox.Text) 
FahrenheitValue = (9/5) * (CelsiusValue + 32) 

else 
die