我正在尝试用vb编写程序,要求用户在华氏文本框中或摄氏文本框中键入一个值。我只想使用ONE按钮执行计算,并使用两个文本框来显示输出,但是我不确定我了解发生了什么。我在文本框中输入的数字不是计算出来的数字。
这里是代码:
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接受并计算输入框中的正确值?
一个主要问题在这里:
FahrenheitValue = (9 / 5) * (CelsiusValue + 32)
CelsiusValue = (5 / 9) * (FahrenheitValue - 32)
除了数学上有些许偏差外,您还需要在再次使用它之前更改值。
即我以摄氏度输入0:
FV现在等于32
尝试此:
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
如果我理解正确,那么如果用户在华氏文本框中输入值,则摄氏温度值将为零。这样,您的华氏值将始终被计算为(9/5)*(0 + 32)。如果相反,它应该可以工作。我认为您需要检查用户在何处输入值,然后根据该值执行相应的计算。
代码将是这样的:
if fahrenheitBox.Text IS Nothing then
CelsiusValue = Val(celsiusBox.Text)
FahrenheitValue = (9 / 5) * (CelsiusValue + 32)
else
die