본문 바로가기
C 언어

SCANF 함수를 이용한 계산기

by treeCoder 2021. 1. 20.

SCANF 함수를 이용한 초간단 계산기이다. 본격적인 계산기로 발전하기에는 어려움이 있어보이는 듯하지만, 하향식 계산기를 이해하는 데 도움이 될 듯하다.

 

/*

  simple calculator implemented via recursive descent

  add_op := + | -
  mul_op := * | /
  digits := {+|-} [0..9] {[0..9]}

  expr   := term {add_op term}
  term   := factor {mul_op factor}
  factor := digits | '(' expr ')'

 */


typedef float calcint_t;
calcint_t expr(void);

char token;

#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>

void error(const char *msg) {
    fputs(msg, stderr);
    exit(1);
}

// match expected and move ahead
void match(char expected) {
    if (token == expected) {
        token = getchar();
        return;
    }

    fprintf(stderr, "Expected %c, got %c", expected, token);
    exit(1);
}


calcint_t factor(void) {
    calcint_t value;

    if (token == '(') {
        match('(');
        value = expr();
        match(')');

    } else if (isdigit(token) || token == '+' || token == '-') {
        ungetc(token, stdin);
        scanf("%f", &value);
        token = getchar();
    } else {
        error("bad factor");
    }

    return value;
}

calcint_t term(void) {
    calcint_t value = factor();

    while (token == '*' || token == '/') {
        switch(token) {
        case '*':
            match('*');

            value *= factor();
            break;

        case '/':
            match('/');
            value /= factor();
            break;

        default:
            error("bad term");
        }
    }

    return value;
}

calcint_t expr() {
    calcint_t value = term();

    while (token == '+' || token == '-') {
        switch(token) {
        case '+':
            match('+');
            value += term();
            break;

        case '-':
            match('-');
            value -= term();
            break;
        default:
            error("bad expr");
        }
    }

    return value;
}

int main(void) {

    token = getchar();
    calcint_t result = expr();
    printf("%f\n", result);

    return 0;
} 

 

그냥 계산기 이해의 용도로만 사용하면 좋을 듯하다.

실행 결과는 아래와 같다.

 

댓글