This program can solve expressions of the following forms: a+b
, a-b
, a*b
, a/b
( a
and b
are numbers :P)
Notice: You can't put spaces in between the operands and the operator, I know this is a limitation and that there are thousands of other ways to achieve a better result, so please don't start complaining about this, it's just a "very simple" two-operand expression 'parser' :)
Very simple two-operand expression 'parser'
#include <stdio.h>
int calc(int op1, int op2, char op);
short op_v(char op);
int main(void)
{
/* Variable declarations */
char op;
int op1, op2;
/* Get the expression */
printf("%s", "Enter a simple expression: ");
/* Break the expression down into tokens and solve it */
if(scanf("%d%c%d", &op1, &op, &op2) == 3 && op_v(op))
printf("%s%d", "Result= ", calc(op1, op2, op));
else
printf("%s", "Invalid expression.\n");
return 0;
}
/* Calculate the result */
int calc(int op1, int op2, char op)
{
switch(op)
{
case '+': return op1+op2;
case '-': return op1-op2;
case '*': return op1*op2;
case '/': return op1/op2;
}
}
/* Validate the operator */
short op_v(char op)
{
switch(op)
{
case '+': return 1;
case '-': return 1;
case '*': return 1;
case '/': return 1;
default: return 0;
}
}
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.