计算器
程序代码:#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define stacksize 201
struct optr
{
char operator[stacksize];
int top;
};
struct optd
{
double data[stacksize];
int top;
};
void pushStackOptr(struct optr *, char );
void pushStackOptd(struct optd *, double );
char getStackOptrTop(struct optr *);
int compareOperator(char, char);
char popStackOptr(struct optr *);
double popStackOptd(struct optd *);
double calculateData(double, double, char);
int main()
{
struct optr *optr;
struct optd *optd;
int i, len;
double sum, x, data1, data2;
char string[201], opt, opt1, opt2;
while(gets(string) && string[0] != '0')
{
//初始化栈、表达式长度
len = strlen(string);
optr = (struct optr *)malloc(sizeof(struct optr));
optd = (struct optd *)malloc(sizeof(struct optd));
if(optr == NULL || optd == NULL)
{
printf("optr,optd");
exit(EXIT_FAILURE);
}
optr->top = optd->top = 0;
//计算表达式的值,使用“算符优先法”
for(i = 0; i < len; i ++)
{
if(string[i] != ' ')
{
if(string[i] >= '0' && string[i] <= '9')
{
x = string[i] - '0';
while(string[i + 1] >= '0' && string[i + 1] <= '9')
{
x = 10 * x + (string[i + 1] - '0');
i ++;
}
//操作数进栈
pushStackOptd(optd, x);
}else
{
//获取栈顶运算符
opt = getStackOptrTop(optr);
switch(compareOperator(opt, string[i]))
{
case 0:
//栈顶优先级低
pushStackOptr(optr, string[i]);
break;
case 1:
//栈顶优先级高
opt = popStackOptr(optr);
data1 = popStackOptd(optd);
data2 = popStackOptd(optd);
sum = calculateData(data1, data2, opt);
pushStackOptd(optd, sum);
i --;
break;
}
}
}
}
//判断算符栈是否为空
while(optr -> top != 0)
{
opt = popStackOptr(optr);
data1 = popStackOptd(optd);
data2 = popStackOptd(optd);
sum = calculateData(data1, data2, opt);
pushStackOptd(optd, sum);
}
//输出计算结果
printf("%.2lf\n",sum);
}
return 0;
}
void pushStackOptr(struct optr *s, char opt)
{
//判断栈满
if(s->top - 1 == stacksize)
{
exit(EXIT_FAILURE);
}
s->operator[s->top ++] = opt;
}
void pushStackOptd(struct optd *s, double x)
{
//判断栈满
if(s->top - 1 == stacksize)
{
exit(EXIT_FAILURE);
}
s->data[s->top ++] = x;
}
char getStackOptrTop(struct optr *s)
{
//判断栈空
if(s->top == 0)
{
return '#';
}
return s->operator[s->top - 1];
}
int compareOperator(char opt1, char opt2)
{
//默认opt1优先级高,opt2优先级高返回0
int flag = 1;
if(((opt1 == '+' || opt1 == '-') && (opt2 == '*' || opt2 == '/')) || opt1 == '#')
{
flag = 0;
}
return flag;
}
char popStackOptr(struct optr *s)
{
//判断栈空
if(s->top == 0)
{
exit(EXIT_FAILURE);
}
return s->operator[-- s->top];
}
double popStackOptd(struct optd *s)
{
//判断栈空
if(s->top == 0)
{
exit(EXIT_FAILURE);
}
return s->data[-- s->top];
}
double calculateData(double data1, double data2, char operator)
{
switch(operator)
{
case '+':
return data2 + data1;
case '-':
return data2 - data1;
case '*':
return data2 * data1;
case '/':
if(data1 == 0)
{
exit(EXIT_FAILURE);
}
return data2 / data1;
}
} 如果只输入一个数计算,则输出这个数怎么改







