用递归实现 计算器代码,进来看看!
#include <stdio.h>#include <conio.h>
#include<stdio.h>
#include<ctype.h>
#include<stdlib.h>
#include <conio.h>
char gain[100];
int n=0;
void information(void) /*报告错误*/
{
printf("=============================================================================\n\n");
printf("*******************************简单计算器************************************\n\n");
printf("**使用说明:输入表达式如, 2*7-5+(2.2/8)=[回车],即按回车结束运算************\n\n");
printf("*******************************祝您计算成功!*********************************\n\n");
printf("=============================================================================\n\n");
}
void error(void)/*报告错误*/
{
printf("ERROR!\n");
exit(1);
}
void match(char wanted)/*标识符匹配*/
{
if(gain[n]==wanted)
gain[++n]=getchar();/*成功则获取下一个标识符 */
else error();
}
double term(void);
double factor(void);
double exp(void)
{
double num=term(); /*计算比加减更高级的运算*/
while((gain[n]=='+')||(gain[n]=='-'))
switch(gain[n])
{
case'+':match('+');
num+=term();
break;
case'-':match('-');
num-=term();
break;
}
return num;
}
double term(void)
{
double div;
double num=factor();/*计算比乘除更高级的运算*/
while((gain[n]=='*')||(gain[n]=='/'))
switch(gain[n])
{
case'*':match('*');
num*=factor();
break;
case'/':match('/');
div=factor();
if(div==0)
{
printf("The divisor is zero!\n");
exit(1);
}
num/=div;
break;
}
return num;
}
double factor(void)
{
double num;
char number[61];
int i=0;
if(gain[n]=='(')
{
match('(');
num=exp();
match(')');
}
else if(isdigit(gain[n])||gain[n]=='.')/*判断字符串是否为浮点数*/
{
while(isdigit(gain[n])||gain[n]=='.')
{
number[i++]=gain[n++];
gain[n]=getchar();
}
number[i]='\0';
num=atof(number); /*把字符串转化为浮点数*/
}
else error();
return num;
}
main()
{
double result;
char t;
information();
do{
printf("\t\t\t\t\t\t\t\t\t\t\t\t\t\t请输入表达式:\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t ");
gain[n]=getchar();
result=exp();
if(gain[n]=='=')
{
gain[n]='\0';
printf("\t\t\t\t\t\t\t\t\t\t\t\t\t\t%s=%f\n",gain,result);
printf("\t\t\t\t\t\t\t\t\t\t\t\tDo you want to go on calculating?(y/n): ");/*询问是否继续*/
getchar(); /*去掉空格*/
scanf("%c",&t);
getchar(); /*去掉空格*/
n=0;
}
else error();
}while(t=='y');
if(t=='n')
printf("\n\t\t\t\t\t\t\t\t\t\t\t\t press any key to stop the progrming"); /*按任意键结束程序*/
getch();
}