カテゴリー
Visual Basic

逆ポーランド記法の計算式

Imports System

Module Program
    Sub Main(args As String())
        Dim rpnstr As String
        Dim rpnary() As String
        Dim ans As Double
        rpnstr = "6.1 5.2 4.3 * + 3.4 2.5 / 1.6 * - "
        While True
            rpnstr = RTrim(rpnstr)
            rpnary = rpnstr.Split(" ")
            If rpnary.Length = 1 Then
                ans = rpnary(0)
                GoTo owari
            End If
            Dim i As Integer = 0
            While True
                If rpnary(i) = "+" Or rpnary(i) = "-" Or rpnary(i) = "*" Or rpnary(i) = "/" Then
                    GoTo mikke
                End If
                i += 1
            End While

mikke:
            Dim a As Double
            Dim b As Double
            a = CDbl(rpnary(i - 2))
            b = CDbl(rpnary(i - 1))
            If rpnary(i) = "+" Then
                rpnary(i - 2) = a + b
            ElseIf rpnary(i) = "-" Then
                rpnary(i - 2) = a - b
            ElseIf rpnary(i) = "*" Then
                rpnary(i - 2) = a * b
            Else
                rpnary(i - 2) = a / b
            End If

            rpnary(i - 1) = ""
            rpnary(i) = ""
            rpnstr = ""

            Dim j As Integer = 0
            For j = 0 To i - 2 - 1
                rpnstr += rpnary(j) + " "
            Next
            rpnstr += CStr(rpnary(i - 2)) + rpnary(i - 1) + rpnary(i) + " "
            For j = i + 1 To rpnary.Length - 1
                rpnstr += rpnary(j) + " "
            Next

        End While
owari:
        Console.WriteLine(ans)
        Console.WriteLine("Hello World!")
    End Sub

コメントを残す

メールアドレスが公開されることはありません。

inserted by FC2 system