#include #include #include static int ch; void error(char *s) { fprintf(stderr, "%s\n", s); exit(EXIT_FAILURE); } void nextch() { do { if ((ch = getchar()) == EOF) return; }while (ch == ' ' || ch == '\t'); } double number() { double x, a; int sign = '+'; if (ch == '+' || ch == '-') { sign = ch; nextch(); } if (! isdigit(ch)) error("Not a number or '(' is required."); x = ch - '0'; nextch(); while (isdigit(ch)) { x = 10 * x + ch - '0'; nextch(); } if (ch == '.') { a = 1; nextch(); while (isdigit(ch)) { x += (a /= 10) * (ch - '0'); nextch(); } } return sign == '-' ? -x : x; } double expression(); double factor() { double x; if (ch != '(') return number(); nextch(); x = expression(); if (ch != ')') error("')' is required,"); nextch(); return x; } double term() { double x, y; x = factor(); while (1) { if (ch == '*') { nextch(); x *= factor(); } else if (ch == '/') { nextch(); y = factor(); if (y == 0) error("Zero division"); x /= y; } else break; } return x; } double expression() { double x; x = term(); while (1) { if (ch == '+') { nextch(); x += term(); } else if (ch == '-') { nextch(); x -= term(); } else break; } return x; } int main() { double x; nextch(); x = expression(); if (ch != '\n') error("Syntax error"); printf("%g\n", x); return EXIT_SUCCESS; }