整数中缀计算器
参照这篇博客的思想,用C制造了一个中缀表达式计算器,支持加减乘除和指数运算仅自然数以及括号,目前还不支持浮点数,效果如图
code如下:
#include <stdio.h>
#include <stdlib.h>
char token;
char err_info_dividedByZero[] = "除你🐴的0";
char err_info_invalidSyntax[] = "瞎🌶? 算式写错了";
int add_or_subtract();
int multiply_or_divide();
int power();
int bracket();
void update_token();
int add_or_subtract()
{
int retval = multiply_or_divide();
while (token == '+' || token == '-')
{
if (token == '+')
{
update_token();
retval += multiply_or_divide();
}
if (token == '-')
{
update_token();
retval -= multiply_or_divide();
}
}
return retval;
}
int multiply_or_divide()
{
int divisor;
int retval = power();
while (token == '*' || token == '/')
{
if (token == '*')
{
update_token();
retval *= power();
}
if (token == '/')
{
update_token();
divisor = power();
if (divisor == 0)
{
fprintf(stdout, "%s\n", err_info_dividedByZero);
system("pause");
exit(1);
}
else
{
update_token();
retval /= divisor;
}
}
}
return retval;
}
int power()
{
int exponent, base;
int retval = bracket();
while (token == '^')
{
update_token();
base = retval;
exponent = bracket(); //这里待会再完善一下
if (exponent == 0)
{
retval = 1;
}
else
{
for (int i = 0; i < exponent-1; i++)
{
retval *= base;
}
}
}
return retval;
}
int bracket()
{
int retval;
if (token == '(')
{
update_token();
retval = add_or_subtract();
if (token != ')')
{
fprintf(stdout, "%s\n", err_info_invalidSyntax);
system("pause");
exit(1);
}
else
{
update_token();
}
}
else if (token >= '0' && token <= '9')
{
ungetc(token, stdin);
scanf("%d", &retval);
update_token();
}
else
{
fprintf(stdout, "%s\n", err_info_invalidSyntax);
system("pause");
exit(1);
}
return retval;
}
void update_token()
{
while((token = getchar()) == ' ');
}
int main(void)
{
system("chcp 65001");
system("cls");
printf("Enter an expression\n>>>");
update_token();
int result = add_or_subtract();
printf("result = %d\n", result);
system("pause");
return 0;
}
由于错误提示的emoji在gbk中没有,编译时编译器需要指定utf-8,否则可能会报错
以后将会加入对于浮点数的支持注
[^注]:也就是说现在🕊了