c++课程设计四则运算 doc 下载本文

int CStr::Judge() //新增程序判断功能 {//三个指针依次遍历字符串,去除空格

//找到除基本运算符和数字外的非法输入 char *destination=source;

while(*destination!=0) {

if('('<=*destination&&*destination<='+'||'-'<=*destination&&*destination<='/'||'0'<=*d }

//找到非法逻辑 destination=pstr;

if(*destination=='^'||*destination=='*'||*destination=='/'||*destination=='+')//一开始

{ return 0;} {destination++;}

//找到非法输入,返回0

char *p,*s,*r,*source=pstr; p=source;s=p+1; while(*p!=0) { }

r=p; if(*p==' ')

{ while(*s!=0) {*p=*s;p++;s++;} }

*p=0;p=r;s=p+1; continue;

p=r+1;s=p+1;

estination&&*destination<='9'||*destination=='^'||*destination==' ')

else{return 0;}

为运算符

int pos_in_opstr; int pos;int z;

char opstr[6]=\

for(pos_in_opstr=0;pos_in_opstr<=4;pos_in_opstr++) { while(charinstr(source,opstr[pos_in_opstr]))

if(*(source+z)=='^'||*(source+z)=='*'||*(source+z)=='/'||*(source+z)=='+'||*(source+z)

if(*(source+z)=='^'||*(source+z)=='*'||*(source+z)=='/'||*(source+z)=='+'||*(source+z)

{return 0;}

//两个运算符相距非法,返回0

{return 0;}

//运算符后紧接着又是运算符,返回0

{

pos=charinstr(source,opstr[pos_in_opstr]); z=pos;

=='-'||*(source+z)==0)

z-=2;

=='-'||*(source+z)==0)

}

}

}

else{source+=pos;} //继续遍历字符串

char m[50];int n=0; strcpy(m,pstr); while(m[n]) { if(m[n]=='(') }

return 1;

cout<<\去除空格后的算式:\

{ }

if(m[n]==')') { } n++;

if(m[n+1]==0) {n++;continue;} {return 0;break;}

//右括号位于结尾,继续

else if('0'<=m[n+1]&&m[n+1]<='9')

//如果右括号右边是数字,没有运算符号,非法,返回0

if(n==0) {n++;continue;}

{return 0;break;}

//左括号位于开头,继续向下遍历

//如果左括号左边是数字,没有运算符号,非法,返回0

else if('0'<=m[n-1]&&m[n-1]<='9')

void main() {

CStr myrecord;

cout<<\cout<<\cout<<\cout<<\cin.get(pause); system(\int choice=1;

//进行退出判断,使程序可以反复运算

cout<<\欢迎使用四则运算程序 \\2 \\n\

cout<<\ cout<<\请按回车键继续 \\2 \\n\

while(choice)

{ char strn[50],duf1[50],duf2[50],duf3[50],duf4[50],duf5[50];

CStr buf1(duf1),buf2(duf2),buf3(duf3),buf4(duf4),buf5(duf5),origin(strn),oristr(strn); int z,lastopen;

cout<<\请输入一个算式\\n\operator >>(cin,oristr); if(oristr.Judge()==0) else

{ cout<<\输入的算式是:\

while(charinstr(&strn[0],'('))

//判断左括号

//输出去除空格后的算式字符串

//判断输入是否合法

{; cout<<\输入有误,请重新输入\\n\

}

}

{ for(z=0;z<=len(&strn[0]);z++) }

//去掉括号后,计算最后剩余的算式

{ if(strn[z]=='(') {lastopen=z;} //找到最后一个左括号的位置 }

}

cout<<\新的式子是:\z=len(&strn[0])+1;

if(strn[z]==')') //找到第一个右括号,将左右括号中的字符串取出计算 {

buf1.midstr(oristr,lastopen+2,z-lastopen-1);

cout<<\在\中,找到\提出进buf3.left(oristr,lastopen);

buf2.right(oristr,len(&strn[0])-z-1); buf1.calculate();

行计算\

//然后将计算后的结果与原先左右括号两边的字符串合并,相当于去掉一对括号

addstrings(&strn[0],addstrings(&duf4[0],buf3.Getstr(),buf1.Getstr()),buf2.Getstr());

oristr.calculate();

cout<<\计算结果为:\

cout<<\退出吗?\\n\继续计算请输入1,退出程序请输入0\cin>>choice; cin.get();

cout<<\现在退出运算!\\n\}

九、程序不足:浮点数的误差问题,上文中提及过;以及不能进行负数运算,曾试图对课本源程序进行此类改进,但最终无果。