我有这个作为我的“长度”的转换程序,我怎么能用最简单的方式来做,而不是保持if,elseif,否则太多,我没有太多经验并试图提高我的编程技巧视觉工作室2008。
基本上,我对公式感到恼火,因为我不知道它是否正确,我使用谷歌但没有帮助,因为我不知道如何在程序从类型转换为类型时正确。
Public Class Form2
Dim Metres As Integer
Dim Centimetres As Integer
Dim Inches As Integer
Dim Feet As Integer
Dim Total As Integer
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ErrorMsg.Hide()
End Sub
Private Sub btnConvert_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConvert.Click
Metres = 1
Centimetres = 0.01
Inches = 0.0254
Feet = 0.3048
txtTo.Text = 0
If txtFrom.Text <> "" Then
If IsNumeric(txtFrom.Text) And IsNumeric(txtTo.Text) Then
If cbFrom.Text = "Metres" And cbTo.Text = "Centimetres" Then
Total = txtFrom.Text * Metres
txtTo.Text = Total
ElseIf cbFrom.Text = "Metres" And cbTo.Text = "Inches" Then
Total = txtFrom.Text * 100
txtTo.Text = Total
ElseIf cbFrom.Text = "Metres" And cbTo.Text = "Feet" Then
ElseIf cbFrom.Text = "Centimetres" And cbTo.Text = "Metres" Then
ElseIf cbFrom.Text = "Centimetres" And cbTo.Text = "Inches" Then
ElseIf cbFrom.Text = "Centimetres" And cbTo.Text = "Feet" Then
ElseIf cbFrom.Text = "Inches" And cbTo.Text = "Metres" Then
ElseIf cbFrom.Text = "Inches" And cbTo.Text = "Centimetres" Then
ElseIf cbFrom.Text = "Inches" And cbTo.Text = "Feet" Then
ElseIf cbFrom.Text = "Feet" And cbTo.Text = "Metres" Then
ElseIf cbFrom.Text = "Feet" And cbTo.Text = "Centimetres" Then
ElseIf cbFrom.Text = "Feet" And cbTo.Text = "Inches" Then
End If
End If
End If
End Sub
End Class
这是我目前所做的事情的来源。
答案 0 :(得分:0)
一种基本方法是通过使用中间格式来分割“从” - 和“到”转换的处理。
所以程序代码类似于这样:
Dim intermediate as Double //Intermediate format in centimeters
Dim result as Double
Dim inputValue as Double = cDbl(txtFrom.Text)
If cbFrom.Text = "Metres" Then
intermediate = inputValue * 100
else if cbFrom.Text = "Centimetres" Then
intermediate = inputValue
else if
...
End If
If cbTo.Text = "Metres" Then
result = intermediate / 100
else if cbTo.Text = "Centimetres" Then
result = intermediate
End If
txtTo.Text = Math.Round(result, 2) //Round optional :)
使用这种方法,您只需担心转换到中间格式和从中间格式转换,您只需处理一次输入和输出格式(而不是为每个输入/输出对编写自定义转换)。