0

我正在编写一个程序来解决二年级方程(例如 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
4

1 回答 1

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))
于 2012-07-18T14:35:33.787 回答