2014-12-13 2 views
-2

VB에서 처음 사용하는 경우 텍스트 상자에서 여러 입력을 시도하면서 텍스트 상자에서 다음을 수행 할 2 차 해결사를 만들고 있습니다. 빈 텍스트 상자에 숫자를 입력하면 'a'라는 변수에 저장되고 일부 연산자 (예 : *, -, /, +, =)가 입력되면 다음 번호가 다른 변수에 저장됩니다.하나의 텍스트 상자에서 여러 입력 받기

기능은 다음과 같습니다.

Dim a As Long 'coefficient of x^2 
Dim b As Long 'coeffecient of x 
Dim c As Long 'constant 
Dim o As String 
Dim ansa As Long 
Dim ansb As Long 
Dim ans As String 
Dim detrmnt As Long 'discriminant 
Private Function solve() 
    detrmnt = (b^2 - 4 * a * c) 
    ansa = (-b + Math.Sqrt(dscmnt))/2 * a ' quadratic formula root1 
    ansb = (-b - Math.Sqrt(dscmnt))/2 * a ' quadratic formula root2 
    ans = ansa & ", " & ansb 
    Return ans 
End Function 

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click 
    solve() 
    TextBox2.Text = solve() 
End Sub 

어떻게하면됩니까?

TextBox1에

는 이차 방정식을 취하고 위에서 상기 변수로 참조 분배,

! - textbox2는 답을 제공합니다.

편집; I가 사용되는 방정식을위한 이차 식이다 (도끼^2 + BX + C = O)

here on wikipedia

정보를 확인;

는 (-b + Math.Sqrt (dscmnt))는는 분모 인 * 뿌리 하나 2 분자이다. 여기

check this formula on wikipedia

, "판별"dscmnt 위는 = B^2-4는 * A * C를, 내가 멀리 가능한 솔루션을 구현에서 수행했기 때문에 항상

+0

입력 상자에서 읽으려는 식을 읽을 수 있도록 입력을 구문 분석해야합니다. 귀하의 질문에 관해서는, 당신은 지금까지 무엇을 가지고 있습니까? – Icepickle

+0

입력을 처리하는 데 필요한 함수가 있지만이 텍스트 상자에 붙어 있습니다. – yawar

+0

@icepickle, "... 입력 내용을 구문 분석 할 수 있습니까?" – yawar

답변

0

, 그래서 먼저 존재 할 수 있습니다 기본 솔루션, 다음 테스트 시나리오 :

텍스트를 구문 분석과 함께 "본격적인"솔루션으로, 당신은 결정해야하는 경우 :

    그들은 A, B의 위치입니다 양 또는 음의 숫자
  • 인 경우
  • 귀하의 입력

가능한 솔루션은 다음과 수 (내가 거기에 확신 해요, C

  • 유효 그것을 할 수있는 더 많은 방법, 그리고 나는 +/-의 구문 분석에 대해 100 % 만족하지는 않지만, 속임수를 쓰면 텍스트를 구문 분석하는 방법에 대한 아이디어를 얻을 수 있습니다.)문제가 해결되지 않을 경우

    참고,이 클래스의 유일한 해결 방법이며, 전체 과도 구현은,이 방법은/오류가 발생, 그래서 중 하나 시도 내에서이 방법을 묶어야합니다

    아래에 다음과 Catch 블록 또는 아래 찾을 수 있습니다 :)

    Public Overrides Sub Resolve(input As String) 
        ' lets say 2x^2 + 4x - 4 = 0 
        ' lets say 5x^2 + 3x + 1 = 0 
        If String.IsNullOrWhiteSpace(input) Then 
         Throw New ArgumentException("Input string cannot be null", "input") 
        End If 
        If input.IndexOf("=") >= 0 Then 
         input = input.Split("=")(0).Trim() 
         If String.IsNullOrWhiteSpace(input) Then 
          Throw New FormatException("'=' is at the beginning of the equation") 
         End If 
        End If 
        If input.Contains(" ") Then 
         input = input.Replace(" ", "") 
        End If 
        Dim lstGroup As New List(Of String) 
        Dim position As Integer = 0 
        Dim delimiters() As String = {"+", "-"} 
        Dim minIndex As Integer 
        Dim curDel As String 
        Dim lastDel As String = "+" 
        Dim part As String 
    
        While position < input.Length 
         minIndex = input.Length 
         curDel = "+" 
         For Each del In delimiters 
          Dim targetIndex As Integer = input.IndexOf(del, position) 
          If targetIndex > 0 AndAlso targetIndex < minIndex Then 
           minIndex = targetIndex 
           curDel = del 
          End If 
         Next 
         part = input.Substring(position, minIndex - position) 
         lstGroup.Add(lastDel + part.ToLower()) 
         position = minIndex + 1 
         lastDel = curDel 
        End While 
    
        CoefficientA = 0 
        CoefficientB = 0 
        CoefficientC = 0 
        For Each group In lstGroup 
         If group.Contains("x^2") Then 
          If CoefficientA <> 0 Then 
           Throw New FormatException("'x^2' was already determined!") 
          End If 
          If Not Integer.TryParse(group.Replace("x^2", ""), CoefficientA) Then 
           ' it is there so set it to 1 
           CoefficientA = 1 
          End If 
          Continue For 
         End If 
         If group.Contains("x") Then 
          If CoefficientB <> 0 Then 
           Throw New FormatException("'x' was already determined!") 
          End If 
          If Not Integer.TryParse(group.Replace("x", ""), CoefficientB) Then 
           CoefficientB = 1 
          End If 
          Continue For 
         End If 
         If CoefficientC <> 0 Then 
          Throw New FormatException("CoefficientC was already determined!") 
         End If 
         CoefficientC = Convert.ToInt32(group) 
        Next 
    End Sub 
    

    위의 방법은 당신이 다음 해결할 수 클래스 수준에 필요한 모든 진정한 값을 설정할 것 TryParse 방법을 사용하여, 당신은해야 기분이 텍스트를 표시 표시됩니다 (테스트 케이스 시나리오 참조)

    위에서 언급했듯이 최상위 구현에서 다소 벗어 났지만 해결해야 할 방정식이 더 많으면 새로운 클래스를 구문 분석하는 데 더 유연한 접근 방식을 사용할 수 있습니다 (Solve/Resolve 메서드 만 필요함). 그리고 그것은 당신에게 몇 가지 가능한 미래의 문제를 절약 할 수있다 : 리졸있다 D)

    테이크, 인터페이스 IEquation를, 및 방법, 그리고 해결 매개 변수

    Public Interface IEquation 
        Sub Resolve(input As String) 
        Sub Solve() 
        ReadOnly Property Solved As Boolean 
    End Interface 
    

    그리고 그 클래스의 경우 MustInherit 구현 해결

    ''' <summary>Abstract implementation of IEquation, offers TryParse & Parse methods,that in their turn refer to the IEquation.Resolve() to do the actual parsing</summary> 
    ''' <remarks>Any implementation of IEquation must have a paramless constructor</remarks> 
    Public MustInherit Class Equation 
        Implements IEquation 
    
        Public Shared Function TryParse(Of T As {New, IEquation})(input As String, ByRef equation As T) As Boolean 
         Dim succeeded As Boolean = True 
    
         Try 
          If String.IsNullOrWhiteSpace(input) Then 
           Throw New ArgumentException("Input string cannot be empty or nothing!", "input") 
          End If 
          equation = Parse(Of T)(input) 
         Catch ex As Exception 
          equation = Nothing 
          succeeded = False 
         End Try 
         Return succeeded 
        End Function 
    
        Public Shared Function Parse(Of T As {New, IEquation})(input As String) As T 
         Dim equation As New T() 
         equation.Resolve(input) 
         Return equation 
        End Function 
    
        Private _solved As Boolean = False 
        Public Property Solved As Boolean 
         Get 
          Return _solved 
         End Get 
         Protected Set(value As Boolean) 
          _solved = value 
         End Set 
        End Property 
    
        Public ReadOnly Property SolvedExplicit As Boolean Implements IEquation.Solved 
         Get 
          Return Solved 
         End Get 
        End Property 
    
        Public MustOverride Sub Resolve(input As String) Implements IEquation.Resolve 
    
        Public MustOverride Sub Solve() Implements IEquation.Solve 
    End Class 
    

    이 클래스는 다음과 같은 이차 방정식으로 생성하고자하는 다른 모든 구문 분석 방정식의 기반으로 사용할 수있는 다음과 같은

    으로 테스트 할 것

    Public Class QuadraticEquation 
        Inherits Equation 
    
        Private _cA As Integer 
        Public Property CoefficientA As Integer 
         Get 
          Return _cA 
         End Get 
         Set(value As Integer) 
          If _cA = value Then 
           Return 
          End If 
          _cA = value 
          Solved = False 
         End Set 
        End Property 
    
        Private _cB As Integer 
        Public Property CoefficientB As Integer 
         Get 
          Return _cB 
         End Get 
         Set(value As Integer) 
          If _cB = value Then 
           Return 
          End If 
          _cB = value 
          Solved = False 
         End Set 
        End Property 
    
        Private _cC As Integer 
        Public Property CoefficientC As Integer 
         Get 
          Return _cC 
         End Get 
         Set(value As Integer) 
          If _cC = value Then 
           Return 
          End If 
          _cC = value 
          Solved = False 
         End Set 
        End Property 
    
        Private _positiveRoot As Decimal 
        Public Property PositiveRoot As Decimal 
         Get 
          Return _positiveRoot 
         End Get 
         Protected Set(value As Decimal) 
          _positiveRoot = value 
         End Set 
        End Property 
    
        Private _negativeRoot As Decimal 
        Public Property NegativeRoot As Decimal 
         Get 
          Return _negativeRoot 
         End Get 
         Protected Set(value As Decimal) 
          _negativeRoot = value 
         End Set 
        End Property 
    
        Public Overrides Sub Resolve(input As String) 
         ' lets say 2x^2 + 4x - 4 = 0 
         ' lets say 5x^2 + 3x + 1 = 0 
         If String.IsNullOrWhiteSpace(input) Then 
          Throw New ArgumentException("Input string cannot be null", "input") 
         End If 
         If input.IndexOf("=") >= 0 Then 
          input = input.Split("=")(0).Trim() 
          If String.IsNullOrWhiteSpace(input) Then 
           Throw New FormatException("'=' is at the beginning of the equation") 
          End If 
         End If 
         If input.Contains(" ") Then 
          input = input.Replace(" ", "") 
         End If 
         Dim lstGroup As New List(Of String) 
         Dim position As Integer = 0 
         Dim delimiters() As String = {"+", "-"} 
         Dim minIndex As Integer 
         Dim curDel As String 
         Dim lastDel As String = "+" 
         Dim part As String 
    
         While position < input.Length 
          minIndex = input.Length 
          curDel = "+" 
          For Each del In delimiters 
           Dim targetIndex As Integer = input.IndexOf(del, position) 
           If targetIndex > 0 AndAlso targetIndex < minIndex Then 
            minIndex = targetIndex 
            curDel = del 
           End If 
          Next 
          part = input.Substring(position, minIndex - position) 
          lstGroup.Add(lastDel + part.ToLower()) 
          position = minIndex + 1 
          lastDel = curDel 
         End While 
    
         CoefficientA = 0 
         CoefficientB = 0 
         CoefficientC = 0 
         For Each group In lstGroup 
          If group.Contains("x^2") Then 
           If CoefficientA <> 0 Then 
            Throw New FormatException("'x^2' was already determined!") 
           End If 
           If Not Integer.TryParse(group.Replace("x^2", ""), CoefficientA) Then 
            ' it is there so set it to 1 
            CoefficientA = 1 
           End If 
           Continue For 
          End If 
          If group.Contains("x") Then 
           If CoefficientB <> 0 Then 
            Throw New FormatException("'x' was already determined!") 
           End If 
           If Not Integer.TryParse(group.Replace("x", ""), CoefficientB) Then 
            CoefficientB = 1 
           End If 
           Continue For 
          End If 
          If CoefficientC <> 0 Then 
           Throw New FormatException("CoefficientC was already determined!") 
          End If 
          CoefficientC = Convert.ToInt32(group) 
         Next 
        End Sub 
    
        Public Sub New() 
    
        End Sub 
    
        Public Overrides Sub Solve() 
         Solved = False 
    
         Try 
          Dim determinant As Decimal 
          Dim squareRootDeterminant As Decimal 
          Dim doubleA As Decimal 
    
          determinant = ((CoefficientB^2) - (4 * CoefficientA * CoefficientC)) 
          If determinant >= 0 Then 
           squareRootDeterminant = Math.Sqrt(Math.Abs(determinant)) 
          Else 
           Throw New InvalidOperationException("Cannot get Square root of negative determinant " & determinant) 
          End If 
          doubleA = 2 * CoefficientA 
    
          PositiveRoot = (-CoefficientB + squareRootDeterminant)/doubleA ' quadratic formula root1 
          NegativeRoot = (-CoefficientB - squareRootDeterminant)/doubleA ' quadratic formula root2 
          Solved = True 
         Catch ex As Exception 
          Solved = False 
          Console.WriteLine("{0}", ex.Message) 
         End Try 
        End Sub 
    
    End Class 
    

    (다시, 약간 구현을 과장)

    Sub Main() 
        Dim test() As String = {"2x^2 + 4x - 4 = 0", "5x^2 + 3x + 1", "2x^2+5x", "x^2+5", "5x - 5 + 3x^2"} 
        Dim eq As IEquation = Nothing 
    
        For Each expression In test 
         Console.WriteLine("Trying to resolve: {0}", expression) 
         If Equation.TryParse(Of QuadraticEquation)(expression, eq) Then 
          eq.Solve() 
          If Not eq.Solved Then 
           Console.WriteLine(vbTab & "Although it could be read, the equation failed to be solved!") 
          Else 
           Dim qe As QuadraticEquation = DirectCast(eq, QuadraticEquation) 
    
           Console.WriteLine(vbTab & "Result: [{0}; {1}]", qe.NegativeRoot, qe.PositiveRoot) 
          End If 
         Else 
          Console.WriteLine("Couldn't be resolved!") 
         End If 
        Next 
    
        Console.ReadLine() 
    End Sub 
    
  • +0

    에 관한 위키피디아 페이지에 대한 링크를 추가했으며, 몇 가지 더 배웁니다. – yawar

    +0

    도와 줘서 기쁩니다 :) – Icepickle

    관련 문제