본문 바로가기
C 언어

strtof 함수를 이용한 계산기

by treeCoder 2021. 1. 21.

strtof 함수를 이용한 계산기를 만들었다.

typedef double calcint_t;
calcint_t expr(void);

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

char *token;

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

// match expected and move ahead
void match(char expected) {
    while (*token && *token == ' ' ) token++; // skip spaces

    if (*token == expected) {
        token++;
        return;
    }

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


calcint_t factor(void) {
    calcint_t value;

    while (*token && *token == ' ' ) token++; // skip spaces

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

    } else if (isdigit(*token) || *token == '+' || *token == '-') {
        
        value = strtof(token, &token); 
        
    } else {
        error("bad factor");
    }

    return value;
}

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

    while (*token && *token == ' ' ) token++; // skip spaces

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

            value *= factor();
            break;

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

        default:
            error("bad term");
        }
        while (*token && *token == ' ' ) token++; // skip spaces
    }

    return value;
}

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

    while (*token && *token == ' ' ) token++; // skip spaces

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

        case '-':
            match('-');
            value -= term();
            break;
        default:
            error("bad expr");
        }
        while (*token && *token == ' ' ) token++; // skip spaces
    }

    return value;
}

int main(int argc, char *argv[]) {

   if( argc != 2 ) {
        printf("\n Enter  numbers as follows. \n\n");
        printf("     %s \" 1  +  32 * 3 -7.5\"\n", argv[0]);
        printf("     %s \" ( 15.3  +  2.4 ) * 23 \"\n", argv[0]);
        printf("     %s \" ( 2.1  -  2.7) * 48.7 \"\n", argv[0]);

        exit(0);
    }
    
    token = argv[1];
    calcint_t result = expr();

    if( *token != '\0' ) {
        fprintf(stderr, "end of expr expected, got \'%s\'", token);
        exit(1);
    }
    
    printf("%f", result);

    return 0;
} 

 실행 결과는 다음과 같다.

 

 

'C 언어' 카테고리의 다른 글

MINGW64 설치하는 방법  (0) 2021.01.22
C 언어에서 right 함수 사용  (0) 2021.01.21
SCANF 함수를 이용한 계산기  (0) 2021.01.20
C 언어를 이용한 계산기 (2)  (0) 2021.01.20
C 언어를 이용한 계산기  (0) 2021.01.16

댓글