作者fumizuki (小獅子)
看板Visual_Basic
標題Re: [VB6 ] 計算機
時間Thu Jun 9 22:21:00 2005
※ 引述《fumizuki (小獅子)》之銘言:
: ※ 引述《TrueFeeling (昨日之死)》之銘言:
: : 表單架構:
: : 0-9 數字鍵--Command1(Index)
: : +-*/鍵 --Command2(Index)
: : Enter --Command3
: 是打算輸入運算式後按enter再算出值?
: 還是像一般計算機一樣按下了加減乘除等於就會算出值?
哇哈!這種運算式真不好寫...好不容易才試了出來...
用遞迴法寫的,寫了一長串,看起來頗複雜的...~.~
Private Sub Command1_Click(Index As Integer)
Text1.Text = Text1.Text & Index
End Sub
Private Sub Command2_Click(Index As Integer)
Text1.Text = Text1.Text & Command2(Index).Caption
End Sub
Private Sub Command3_Click()
Label1.Caption = Eval(Text1.Text)
End Sub
Function Eval(s As String)
Dim p As Integer, op1 As String, op2 As String, o As String
Static c As Integer: c = c + 1
If c = 1 Then s = Replace(s, " ", "")
p = InStr(s, "+")
If p > 0 Then GoSub SplitProc: Eval = Eval(op1) + Eval(op2): GoTo EndProc
If s Like "-*" Then p = 2 Else p = 1
p = InStr(p, s, "-")
If p > 0 Then
op1 = Mid(s, p - 1, 1)
If op1 = "+" Then
p = p - 1: GoSub SplitProc: Eval = Eval(op1) + Eval(op2): GoTo EndProc
ElseIf op1 = "-" Then
p = p - 1: GoSub SplitProc: Eval = Eval(op1) - Eval(op2): GoTo EndProc
ElseIf op1 = "*" Then
p = p - 1: GoSub SplitProc: Eval = Eval(op1) * Eval(op2): GoTo EndProc
ElseIf op1 = "/" Then
p = p - 1: GoSub SplitProc: Eval = Eval(op1) / Eval(op2): GoTo EndProc
Else
GoSub SplitProc: Eval = Eval(op1) + Eval("-" & op2): GoTo EndProc
End If
End If
p = InStr(s, "*")
If p > 0 Then GoSub SplitProc: Eval = Eval(op1) * Eval(op2): GoTo EndProc
p = InStr(s, "/")
If p > 0 Then GoSub SplitProc: Eval = Eval(op1) / Eval(op2): GoTo EndProc
Eval = Val(s)
EndProc:
c = c - 1: Exit Function
SplitProc:
op1 = Left(s, p - 1): op2 = Mid(s, p + 1): Return
End Function
1. 事件程序的命名規則及參數列是寫死的,一定要完全一樣,不然無法通過編譯。
2. Or、And 等運算子跟 + - * / 一樣,一定會算出一個值。
(語法沒錯,執行結果不對而已)
3. N 跟 "N" 是不相同的,一樣語法沒錯,但執行結果不對...
...
測試通過才貼上來的,應該是沒有問題的吧(汗)
? Eval("-2.3 * -3 / -7 + -5.6 - -6 + -2 + -3 * -2 / -1 + -0.5")
? -2.3 * -3 / -7 + -5.6 - -6 + -2 + -3 * -2 / -1 + -0.5
-9.08571428571429
-9.08571428571429
以上...XD
加、減、乘、除、負號,運算子優先順序,都有包含在內了...XD
--
VB 程式設計 倉木麻衣 PTT 星爺板 行列輸入法
======================================================
Visual_Basic MaiKuraki Stephen Array
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 210.58.156.43