Declare Function printf CDECL Lib"msvcrt" (fmt As *Byte, ...) As Long Declare Function getchar CDECL Lib"msvcrt" () As Long Declare Function isdigit CDECL Lib"msvcrt" (c As Long) As Long Declare Function cexit CDECL Lib"msvcrt" Alias "exit" (c As Long) As Long
Dim ch As Long
Sub error(s As *Byte) /* エラー処理 */ printf(Ex"%s\n", s): cexit(1) End Sub
Sub readch() /* 1文字を読む. 空白は読み飛ばす. */ Do ch = getchar() If (ch = -1) Then Exit Sub Loop while (ch = Asc(Ex" ") Or ch = Asc(Ex"\t")) End Sub
Function number() As Double /* 数 */ Dim x As Double, a As Double Dim sign As Long If (ch = Asc(Ex"+") Or ch = Asc(Ex"-")) Then sign = ch: readch() End If If (isdigit(ch) = 0) Then error(Ex"数か '(' がありません") x = ch - Asc(Ex"0") while (1) readch() If isdigit(ch) <> 0 Then x = 10 * x + ch - Asc(Ex"0") Else Exit While End If Wend if (ch = Asc(Ex".")) Then a = 1 while (1) readch() If isdigit(ch) <> 0 Then a = a / 10 x = x + (a) * (ch - Asc(Ex"0")) Else Exit While End If Wend End If If (sign = Asc(Ex"-")) Then number = -x Else number = x End Function
Function factor() As Double /* 因子 */ Dim x As Double
If (ch <> Asc(Ex"(Ex")) Then factor = number() Exit Function End If readch(): x = expression() If (ch <> Asc(Ex")")) Then error(Ex"')' がありません") readch(): factor = x End Function
Function term() As Double /* 項 */ Dim x As Double, y As Double
x = factor() While (1) If (ch = Asc(Ex"*")) Then readch(): x = x * factor() Else If (ch = Asc(Ex"/")) Then readch(): y = factor() If (y = 0) Then error(Ex"0 では割れません") x = x / y Else Exit While End If Wend term = x End Function
Function expression() As Double /* 式 */ Dim x As Double
x = term() While (1) If (ch = Asc(Ex"+")) Then readch(): x = x + term() Else if (ch = Asc(Ex"-")) Then readch(): x = x - term() Else Exit While End If Wend expression = x End Function
Sub main() Dim x As Double
readch(): x = expression() If (ch <> Asc(Ex"\n")) Then error(Ex"文法の間違いがあります") printf(Ex"%g\n", x) End Sub main()