C语言编程实训 简易计算机

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

#include

#include

char ch;

void match(char expectedch)/*对当前的标志进行匹配*/

{

if(ch==expectedch)

ch=getchar();/* 匹配成功,获取下一个标志*/ else

printf("cannot match\n");

}

int low()/*用于计算表达式中级别最低的运算*/

{

int mid( );

int result=mid();

while((ch=='+')||(ch=='-'))

if(ch=='+')

{

match('+');

result+=mid();

break;

}

else if(ch=='-')

{

match('-');

result-=mid();

break;

}

return result;

}

int mid()

{

void menu();

int div;/*除数*/

int high(void);

int result=high();

while((ch=='*')||(ch=='/'))

if(ch=='*')

{

match('*');

result*=high();

break;

}

else if(ch=='/')

{

match('/');

div=high();

if(div==0)/*判断除数是否为0*/

{

system("cls");/*清屏*/

printf("除数为0,请重新输入:\n");

menu();

exit(0);

}

result/=div;

break;

}

return result;

}

int high()

{

void menu();

int result;

if( ch=='(')/*带有括号的运算*/

{

match('(');

result=low();/*递归计算表达式*/

match(')');

}

else if(ch>='0'&&ch<='9')

{

ungetc(ch,stdin);

scanf("%d",&result);

ch=getchar();

}

else

{

system("cls");

printf("请重新输入:\n");/*不是括号也不是数字*/ menu();

}

return result;

}

void menu()

{

int WH;

int result;

Wang:

puts("\t+---------------------+");

puts("\t| Simple Calculator |");

puts("\t+---------------------+");

puts("\t| |");

puts("\t+-----+----+----+-----+");

puts("\t| | / | * | - |");

puts("\t+-----+----+----+-----+");

puts("\t| 7 | 8 | 9 | |");

puts("\t+-----+----+----+ + |");

puts("\t| 4 | 5 | 6 | |");

puts("\t+---------------------+");

puts("\t| 1 | 2 | 3 | |");

puts("\t+-----+----+----+ = |");

puts("\t| 0 | . | |");

puts("\t+---------------------+");

ch=getchar();

result=low();

if(ch=='\n')/*是否一行结束*/

printf("the answer is:%d\n",result);

else

printf("请重新输入:\n");

printf("\n 1-继续计算;2-退出系统\n");

scanf("%d",&WH);getchar();

if(WH==1)

{

system("cls");//清屏

goto Wang; //调用菜单函数

}

else

exit(0); //退出系统

}

void main()

{

menu();

}

相关文档
最新文档