본문 바로가기
C 언어

C 언어를 이용한 계산기

by treeCoder 2021. 1. 16.

C 언어를 이용한 계산기를 만들어 보았다.

 

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

char *x;

double mult();
double add();
double factor();
double parseFormula();
double parseNumber();

double add() {
  double pro1=mult();
  while(*x && *x == ' ') x++; //skip spaces
  
  while(*x=='+' || *x=='-') {
   char op = *x++;
   double pro2 = mult();
   while(*x && *x == ' ') x++; //skip spaces
   if(op == '+') pro1 = pro1 + pro2;
   if(op == '-') pro1 = pro1 - pro2;
  }
  return pro1;
}

double mult() {
  double fac1=factor();
  while(*x && *x == ' ') x++; //skip spaces
  
  while(*x == '*' || *x == '/') {
    char op = *x++;
    double fac2=factor();
    while(*x && *x == ' ') x++; //skip spaces
    if(op =='*') fac1 = fac1 * fac2;
    if(op =='/') {
       if( fac2 == 0.0 ) {
           puts("Error: division by zero.");
           exit(0);
       }
       fac1 = fac1 / fac2;
    }
  }
  return fac1;
}

double factor() {
  while(*x && *x == ' ') x++; //skip spaces
  
  if(*x>='0' && *x<='9') {
    return parseNumber();
  } else if(*x=='(') {
    ++x; // Consume (
    double sum = add();
    ++x; // Consume )
    return sum;
  } else {
    printf("unexpected %c", *x);
  }
}

double parseNumber() {
    double number = 0;
    while( *x >= '0' && *x <= '9') {
       number = number * 10;
       number = number + *x - '0';
       ++x;
    }
    if( *x == '.') {
       ++x;// Consume .
       double weight = 1;
       while( *x >= '0' && *x <= '9') {
          weight = weight / 10;
          double scaled = (*x - '0') * weight;
          number = number + scaled;
          ++x;
       }
    }
    return number;
}

double parseFormula() {
    double result = add();
    if(*x == '\0') {
       return result;
    }
    printf("expected end of input but found %c\n", *x);
}

int main(int argc, char * argv[] ) {
  //char s[512];

  //s[0]='\0';

  //fgets(s, sizeof(s)-1, stdin);
  
  if( argc != 2 ) {
      puts("\n Enter  numbers as follows. \n");
      puts(" cal \" 1  +  32 * 3 -7.5\"");
      puts(" cal \" ( 15.3  +  2.4 ) * 23 \"");
      puts(" cal \" ( 2.1  -  2.7) * 48.7 \"");
      return 0;
  }

  x = argv[1];
  double ans= parseFormula();
  printf("%f", ans);
  return 0;
}

 

성공적으로 컴파일하였다면 실행 결과는 아래와 같다.

 

댓글