我的计算器(参见代码打击)仅计算整数值。但是我想用实数操作(ex 12.24 + 11.06 =)
您可以帮我修改下面的计算器代码吗?我编程得不是很好,我刚开始学习,所以非常感谢你的帮助。
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 50
#define SUM(X,Y) (X)+(Y)
#define MULTI(X,Y) (X)*(Y)
#define DIV(X,Y) (X)/(Y)
typedef struct _Stack
{
char Operator[MAX];
int Operand[MAX];
int Opt_top;
int Opd_top;
}Stack;
Stack stack;
void init()
{
stack.Opd_top = stack.Opt_top = 0;
}
void optPush(char opt)
{
stack.Operator[stack.Opt_top++] = opt;
}
void opdPush(int opd)
{
stack.Operand[stack.Opd_top++] = opd;
}
char optPop()
{
return stack.Operator[--stack.Opt_top];
}
int opdPop()
{
return stack.Operand[--stack.Opd_top];
}
void resetExpression(char Exp[], int len)
{
for (int i = 0; i < len; i++)
Exp[i] = '\0';
}
int optCheck(char opt1, char opt2)
{
if (opt1 == '*' || opt1 == '/')
{
if (opt2 == '+' || opt2 == '-')
return 1;
else
return 0;
}
else
return 0;
}
int calFunc(int opd1, int opd2, char opt)
{
int result;
switch (opt)
{
case '+':
result = SUM(opd1, opd2);
break;
case'*':
result = MULTI(opd1, opd2);
break;
case'/':
result = DIV(opd1, opd2);
break;
}
return result;
}
void calEngine(char Exp[], int len) {
char tmpExp[MAX] = { 0, };
char ch, opt;
int tmpCnt = 0, opd1, opd2, res, flag = 0;
for (int i = 0; i < len; i++) {
ch = Exp[i];
if (ch == ' ')
continue;
else if (ch >= '0' && ch <= '9') {
tmpExp[tmpCnt++] = ch;
if (Exp[i + 1] == '(' || Exp[i + 1] == ')' || Exp[i + 1] == '+' || Exp[i + 1] == '-' || Exp[i + 1] == '*' || Exp[i + 1] == '/' || Exp[i + 1] == '=')
{
if (flag)
{
flag = 0;
opdPush(-atoi(tmpExp));
}
else
opdPush(atoi(tmpExp));
resetExpression(tmpExp, tmpCnt);
tmpCnt = 0;
}
}
else
if (ch == '+' || ch == '-' || ch == '*' || ch == '/')
{
if (ch == '-') {
flag = 1;
ch = '+';
}
if (stack.Opt_top == 0)
optPush(ch);
else
{
opt = optPop();
if (optCheck(opt, ch))
{
opd2 = opdPop();
opd1 = opdPop();
res = calFunc(opd1, opd2, opt);
opdPush(res);
optPush(ch);
}
else {
optPush(opt);
optPush(ch);
}
}
}
else if (ch == '(')
optPush(ch);
else if (ch == ')') {
while (opt != '(') {
opt = optPop();
if (opt != '(') {
opd2 = opdPop();
opd1 = opdPop();
res = calFunc(opd1, opd2, opt);
opdPush(res);
}
}
}
else if (ch == '=')
break;
}
while (stack.Opt_top != 0)
{
opd2 = opdPop();
opd1 = opdPop();
printf("opd1:%d opd2:%d\n", opd1, opd2);
opt = optPop();
printf("opt: %c\n", opt);
res = calFunc(opd1, opd2, opt);
printf("result:%d\n", res);
opdPush(res);
}
}
int main(void)
{
int j = 1;
while (j <= 100)
{
printf("%d 번째 계산\n",j);
char Expression[MAX] = { 0, };
printf("식 입력: ");
gets(Expression);
calEngine(Expression, strlen(Expression));
printf("%d 번째 계산결과=%d\n\n", j,opdPop());
j++;
}
return 0;
}