2016-10-08 3 views
1

Как я могу заставить этот калькулятор работать, если пользователь вводит 1 + 1? Он работает только при вводе 1 + 1; C Расчет должен быть в 1 строке.Расчет в 1 строке VBS

x = inputbox("Calculation", "Calculator", "1+1") 
y = Split(x) 
if not isnumeric (y(0)) then 
wscript.quit 
end if 
if not isnumeric (y(2)) then 
wscript.quit 
end if 
if y(1) = "+" then 
z = int(y(0)) + int(y(2)) 
msgbox(z) 
end if 
if y(1) = "-" then 
z = int(y(0)) - int(y(2)) 
msgbox(z) 
end if 
if y(1) = "*" then 
z = int(y(0)) * int(y(2)) 
msgbox(z) 
end if 
if y(1) = "/" then 
z = int(y(0))/int(y(2)) 
msgbox(z) 
end if 
if y(1) = "%" then 
z = int(y(0)) MOD int(y(2)) 
msgbox(z) 
end if 

благодарит за любой ответ!

ответ

3

Попробуйте следующий фрагмент кода (с комментариями для объяснения):

Dim ii, sOperator, strExpr, y 
strExpr = inputbox("Calculation", "Calculator", "1+1") 

' insert spaces around all operators 
For Each sOperator in Array("+","-","*","/","%") 
    strExpr = Trim(Replace(strExpr, sOperator, Space(1) & sOperator & Space(1))) 
Next 
' replace all multi spaces with a single space 
Do While Instr(strExpr, Space(2)) 
    strExpr = Trim(Replace(strExpr, Space(2), Space(1))) 
Loop 

y = Split(strExpr) 
''' your script continues here 

Другой подход (позволяет более чистых арифметических операций) с помощью Eval Function (который вычисляет выражение и возвращает результат) и Основная error handling:

option explicit 
On Error GoTo 0 

Dim strResult: strResult = Wscript.ScriptName 
Dim strExpr, strInExp, strLastY, yyy 
strInExp = "1+1" 
strLastY = "" 
Do While True 

    strExpr = inputbox("Last calculation:" & vbCR & strLastY, "Calculator", strInExp) 

    If Len(strExpr) = 0 Then Exit Do 

    ''' in my locale, decimal separator is a comma but VBScript arithmetics premises a dot 
    strExpr = Replace(strExpr, ",", ".") ''' locale specific 

    On Error Resume Next    ' enable error handling 
    yyy = Eval(strExpr) 
    If Err.Number = 0 Then 
    strInExp = CStr(yyy) 
    strLastY = strExpr & vbTab & strInExp 
    strResult = strResult & vbNewLine & strLastY 
    Else 
    strLastY = strExpr & vbTab & "!!! 0x" & Hex(Err.Number) & " " & Err.Description 
    strInExp = strExpr 
    strResult = strResult & vbNewLine & strLastY 
    End If 
    On Error GoTo 0     ' disable error handling 
Loop 

Wscript.Echo strResult 
Wscript.Quit 

Образец выходного сигнала:

==> cscript //NOLOGO D:\VB_scripts\SO\39934370.vbs 
39934370.vbs 
1+1  2 
2/4  0,5 
0.5**8 !!! 0x3EA Syntax error 
0.5*8 4 
4=4  True 
True+5 4 
4=5  False 
False+5 5 
5  5 

==>