#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>char *p, *src;
void error(const char *s){
printf("%s\n", src);
char fmt[80];
sprintf(fmt, "%%%lds\n", p - src);
printf(fmt, "^");printf("错误:%s\n", s);
exit(EXIT_FAILURE);
}int c;
float val;float num(){
while (isspace(c = *p)){
p++;
}
bool sign = false;
if (c == '+'){
c = *++p;
}else if (c == '-'){
sign = true;
c = *++p;
}
while (isspace(c = *p)){
p++;
}
if (isdigit(*p) == 0){
error("缺少数字");
}int x = 0;
float xx = 0;
bool bxx = 0;
int n=0;
while (isdigit(c = *p) || c == '.'){
if (c == '.'){
bxx = 1;
p++;
continue;
}
if (!bxx)
x = x * 10 + (c - '0');
else{
xx +=((c - '0') /pow(10,++n));
}
p++;
}
while (isspace(c = *p)){
p++;
}
float val = (float)x +xx;
return sign ? -val : val;
}
float m(){
float mx = num();
while (c == '*' || c == '/'){
++p;
if (c == '*'){
mx *= num();
}else{
mx /= num();
}
}
return mx;
}
void parse(){
if (c == '+'){
c = *++p;
val += m();
}else if (c == '-'){
c = *++p;
val -= m();
}else{
error("缺少运算符");
}
}float calc(){
p = src;
c = *p;
val = 0;
if (c){
val = m();
while(c) parse();
}
return val;
}/*
1 + 2 * 3
42 *3.14159
1+2*3/4-5
1/2/3/4/5
*/
int main(){
src = p = (char *)malloc(1024);
while (fgets(src, 1024, stdin)){
char *ptr = strchr(src, 10);
if (ptr)*ptr = 0;
printf("=%f\n", calc());
}
free(src);
return 0;
}
C语言,基于递归下降的计算器程序。缺点,不支持小括号。
最新推荐文章于 2024-10-06 10:17:48 发布