我正在制作一个程序来解决二级方程(例如2x²+ 2x + 2),我试图让用户在一个文本框中输入整个方程。然后,计算机将键入文本框的内容存储在字符串中,然后解析字符串以查找系数。对于像2x²+ 2x + 2这样的等式,系数是2,2和2,它们存储在0,4和7位的字符串中。最大的问题是,如果它是一个更大的等式,如32x²+ 32x + 45或123x²+ 45x + 6?在那种情况下,我的逻辑不起作用。有谁知道怎么做?
这是我的代码,仅适用于小方程:
Public Class Form1
Dim i1 As Double
Dim i2 As Double
Dim i3 As Double
Dim delta As Double
Dim x1 As Double
Dim x2 As Double
Dim leters As String
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
i1 = T1.Text
i2 = T2.Text
i3 = T3.Text
delta = (i2 * i2) - 4 * (i1 * i3)
If (delta < 0) Then
Ld.Text = delta
L1.Text = "Impossível"
L2.Text = "Impossível"
Else
x1 = (-i2 + Math.Sqrt(delta)) / (2 * i1)
x2 = (-i2 - Math.Sqrt(delta)) / (2 * i1)
Ld.Text = delta
L1.Text = x1
L2.Text = x2
End If
End Sub
Private Sub RadioButton1_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RadioButton1.CheckedChanged
GroupBox1.Text = "Equação"
GroupBox1.Width = 200
GroupBox1.Height = 58
T1.Width = 188
T3.Hide()
T2.Hide()
Label1.Hide()
Button1.Hide()
Button2.Show()
End Sub
Private Sub RadioButton2_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles RadioButton2.CheckedChanged
GroupBox1.Text = "Coeficientes"
GroupBox1.Width = 200
GroupBox1.Height = 143
T1.Width = 119
T3.Show()
T2.Show()
Label1.Show()
Button1.Show()
Button2.Hide()
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
leters = T1.Text
leters.ToString()
End Sub
End Class
答案 0 :(得分:1)
您可以使用RegEx来解析字符串,这很好,因为您可以将RegEx表达式更改为设置而不重建程序集。但是,如果方程字符串格式总是相同的,就像这里的情况一样(因为其余的代码如果不是则会失败),那么你可以简单地使用String.Split
来解析字符串。例如:
Dim equation As String = "32x²+32x+45"
Dim parts() As String = equation.Split(New Char() {"+"c, "x"c}, StringSplitOptions.RemoveEmptyEntries)
Dim coefficient1 As Integer = Integer.Parse(parts(0))
Dim coefficient2 As Integer = Integer.Parse(parts(2))
Dim coefficient3 As Integer = Integer.Parse(parts(3))