i need help on how to make a calculator program on C.

for example:
100+3*(344-45)-3/20= ?

ive done a part of it, but it doesnt even give the right answer. the user inputs anything (excluding letters and some puncts). it accepts the equation as a string. ive already converted the string into integers using atoi() fn but im stucked and i dont know what to do next. i made a program similar to this but it doesnt follow the precedence of the operators and it cant compute the answer when you include parenthesis on it...

I need help badly! thanks....

*anything from telling me what to do next will do or any other will do* ill just try to analyze all your answers and see if i can really get it... :lol:

Dani AI

Generated

described the classic problem: parsing infix expressions with correct precedence and parentheses. 's suggestion to use postfix (RPN) plus a stack is the right direction. Below is a compact, practical pipeline: tokenize the input, run Dijkstra's shunting‑yard to produce RPN, then evaluate the RPN with a stack of doubles. This example handles precedence, parentheses, unary minus and floating-point numbers (avoid atoi for general expressions).

Key points to implement: recognize numbers with strtod, detect operators + - * / ^, treat a leading or parentheses-following - as unary (insert 0 before it), use precedence and associativity rules in the shunting yard, and evaluate RPN by popping two operands for each binary operator. Common pitfalls are integer division (3/20 == 0 for ints), mismatched parentheses, and forgetting right-associativity for ^.

A minimal, practical example (infix -> RPN -> eval):

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

int prec(char op){ if(op=='+'||op=='-') return 1; if(op=='*'||op=='/') return 2; if(op=='^') return 3; return 0; }
int is_right_assoc(char op){ return op=='^'; }

void infix_to_rpn(const char *in, char *out){
    char ops[256]; int top=-1, outpos=0; char last=0;
    while(*in){
        if(isspace((unsigned char)*in)){ in++; continue; }
        if(isdigit((unsigned char)*in) || *in=='.'){ char num[64]; int n=0;
            while(*in && (isdigit((unsigned char)*in)||*in=='.')) if(n<63) num[n++]=*in++; num[n]=0;
            outpos += snprintf(out+outpos, 1024-outpos, "%s ", num); last='n'; continue;
        }
        if(*in=='+'||*in=='-'||*in=='*'||*in=='/'||*in=='^'){
            char cur=*in;
            if(cur=='-' && (last==0 || last=='(' || last=='o')) outpos += snprintf(out+outpos,1024-outpos,"0 ");
            while(top>=0 && ops[top]!='('){
                int ptop=prec(ops[top]), pcur=prec(cur);
                if(ptop>pcur || (ptop==pcur && !is_right_assoc(cur))){ out[outpos++]=ops[top--]; out[outpos++]=' '; } else break;
            }
            ops[++top]=cur; last='o'; in++; continue;
        }
        if(*in=='('){ ops[++top]='('; last='('; in++; continue; }
        if(*in==')'){ while(top>=0 && ops[top]!='('){ out[outpos++]=ops[top--]; out[outpos++]=' '; } if(top>=0) top--; last=')'; in++; continue; }
        in++; /* skip unknown */
    }
    while(top>=0){ out[outpos++]=ops[top--]; out[outpos++]=' '; }
    out[outpos]=0;
}

double eval_rpn(char *rpn){
    double st[256]; int top=-1;
    char *tok=strtok(rpn," ");
    while(tok){
        if(isdigit((unsigned char)tok[0]) || tok[0]=='.' || (tok[0]=='-' && isdigit((unsigned char)tok[1]))) st[++top]=strtod(tok,NULL);
        else{ double b=st[top--], a=st[top--], r=0;
            switch(tok[0]){ case '+': r=a+b; break; case '-': r=a-b; break; case '*': r=a*b; break; case '/': r=a/b; break; case '^': r=pow(a,b); break; }
            st[++top]=r;
        }
        tok=strtok(NULL," ");
    }
    return top>=0?st[top]:0;
}

/* Usage example:
   char rpn[1024]; infix_to_rpn("100+3*(344-45)-3/20", rpn);
   char copy[1024]; strcpy(copy,rpn); printf("%s = %.10g\n", rpn, eval_rpn(copy));
*/

Troubleshooting notes: use strtod (not atoi) to avoid integer-only results; check for division by zero; validate parentheses and illegal characters; increase buffer sizes for very long expressions; extend the tokenizer to support functions (sin, log) by treating them as special tokens in the shunting yard. This snippet should be a solid, focused starting point for the calculator described by and the follow-up from .

Recommended Answers

All 3 Replies

Oddly enough, I answered this very question on another forum yesterday. The trick is to convert the expression to postfix so that you can easily evaluate it with a stack based approach. Alternatively, you could build an expression parse tree, but that just adds extra unnecessary steps in most cases.

Please read the Announcement.

Though I can't specifically say that you're doing a homework problem, the signs are there. We don't do work for you. Please post some code, and we'll help you troubleshoot.

i need help on how to make a calculator program on C.

for example:
100+3*(344-45)-3/20= ?

ive done a part of it, but it doesnt even give the right answer. the user inputs anything (excluding letters and some puncts). it accepts the equation as a string. ive already converted the string into integers using atoi() fn but im stucked and i dont know what to do next. i made a program similar to this but it doesnt follow the precedence of the operators and it cant compute the answer when you include parenthesis on it...

I need help badly! thanks....

*anything from telling me what to do next will do or any other will do* ill just try to analyze all your answers and see if i can really get it... :lol:

did you already fix this????? i ned program like yours too.........
could you help me?????please??????????/

commented: Epic fail. -4
commented: Reading isn't your strongest point is it? -2
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.