源代码如下:- program expression_calculator;
- uses windows,dos;
- label calc,head;
- var
- a,r:string;
- f,n:array [1..100] of string;
- i,j,k,l,lqu,rqu:integer;
- t,u:real;
- fl1,fl2:text;
- p:boolean;
- begin
- a:=paramstr(1);
- a:='('+a+')';
- p:=false;
- if paramstr(2)='/p' then p:=true;
- head:write('');
- assign(fl1,'calc.mfc');
- assign(fl2,'calc.mfc');
- for i:=1 to 100 do begin
- f[i]:='';
- n[i]:='';
- end;
- lqu:=0;
- rqu:=length(a);
- for i:=1 to length(a) do begin
- if a[i]='(' then lqu:=i;
- if a[i]=')' then begin rqu:=i;goto calc end;
- end;
- calc:j:=1;
- for i:=lqu to rqu do
- case a[i] of
- '1','2','3','4','5','6','7','8','9','0','.':n[j]:=n[j]+a[i];
- '+','-','*','/':begin j:=j+2;f[j-1]:=a[i] end;
- end;
- for i:=2 to j do
- for k:=i-1 downto 1 do
- if n[k]<>'' then
- for l:=i+1 to j do
- if n[l]<>'' then begin
- val(n[k],t);
- val(n[l],u);
- case f[i] of
- '*':begin rewrite(fl1);t:=t*u;write(fl1,t:0:5);close(fl1);reset(fl2);read(fl2,n[i]);close(fl2);n[k]:='';n[l]:='';f[i]:='' end;
- '/':begin rewrite(fl1);t:=t/u;write(fl1,t:0:5);close(fl1);reset(fl2);read(fl2,n[i]);close(fl2);n[k]:='';n[l]:='';f[i]:='' end;
- end;
- end;
- for i:=2 to j do
- for k:=i-1 downto 1 do
- if n[k]<>'' then
- for l:=i+1 to j do
- if n[l]<>'' then begin
- val(n[k],t);
- val(n[l],u);
- case f[i] of
- '+':begin rewrite(fl1);t:=t+u;write(fl1,t:0:5);close(fl1);reset(fl2);read(fl2,n[i]);close(fl2);n[k]:='';n[l]:='';f[i]:='' end;
- '-':begin rewrite(fl1);t:=t-u;write(fl1,t:0:5);close(fl1);reset(fl2);read(fl2,n[i]);close(fl2);n[k]:='';n[l]:='';f[i]:='' end;
- end;
- end;
- r:='';
- for i:=1 to j do
- if n[i]<>'' then r:=n[i];
- delete(a,lqu,rqu+1-lqu);
- insert(r,a,lqu);
- if p then writeln(a);
- if not((pos('+',a)=0) and (pos('-',a)=0) and (pos('*',a)=0) and (pos('/',a)=0)) then goto head;
- if not(p) then writeln(a);
- exec('C:\Windows\system32\cmd.exe','/c del /f /q calc.mfc >nul 2>nul');
- end.
复制代码 使用方法:calcu [表达式]
支持多重括号,如:(((32-5)*2)-65)+3,实数运算保留5位小数。请确保输入的表达式格式正确,否则会发生不可预料的错误。
目前仅支持四则运算。
更新:增加/p开关,/p开关必须在表达式后面,若有/p开关,则给出计算过程。
Bug:不能处理负数,将会尽快修复。
链接: https://pan.baidu.com/s/1LHxoZW6rL1jNxisiMxApVw?pwd=wit7 |