Hello, I meant with a simple calculating which just using the operators (+ - * / ) and entering the simple calculator's equation as a string.. e.g: "3+9/6+2" which the return must be the result of this simple math equation as the result in this case is, 4, (begin from the left to the end with ignorantly of the precedences) .
I've been struggling about a complete day -new programmer -and there's no errors but just getting incorrect result's answer , I checked/reviewed it more than once and I dont know why it's not working fine though all functions go well!!
can anyone help me or actually gimme a hint for modifying and fix my code to work correctly in proper way?
here is my code:
Code:
#include<stdio.h>
#include <string.h>
#include<stdlib.h>
double evaluate(char expr[]);
int main()
{
char expr[21];
double ssum=0;
printf("Input ur string:\n");
scanf("%20s",&expr);
sssum = evaluate(expr);
printf("Output: %.2lf", sssum);
return 0;
}
double evaluate(char expr[])//this function for evaluating the value of the four equation's calculation//
{
char n='r';//doesn't matter what's the string because the code itself pushes it immediately after getting a new string//
int i=0,j=0;
float temp2=0,temp=0;
while (i<strlen(expr))
{
while (1)//this function for obtaining the whole number(complete number) until we arrive to any operators of +-*///
{
temp=temp*10+(expr[i]-'0');
i+=1;
if (expr[i]=='+' || expr[i]=='/' || expr[i]=='*'|| expr[i]=='-') break;
}
switch (expr[i])//after getting out of the second while, the code will proceed to swtich function)
{
case '+':// by the way temp2 is the collecting of all the values in all cases which at the end the final answer included in it//
{
n='+';
temp2+=temp;
temp=0;
break;
}
LINE2:
case '-':
n='-';
if(temp2==0)
{
temp2=temp-temp2;
temp=0;
break;
}
else
{
temp2=temp2-temp;
temp=0;
break;
}
LINE3:
case '*':
n='*';
if ((expr[0]-'0')!=0)
{
temp2=1;
temp2=temp2*temp;
temp=0;
break;
}
else
{
temp2=temp2*temp;
temp=0;
break;
}
case '/':
temp2=1;
temp2/=temp;
temp=0;
break;
default:
temp2+=temp;
break;
}
i+=1;
}
return temp2;
}
I tired hard to find what's the trouble in my code, unfortunately didn't figure out, it's almost done but need some finishes and modifications so please would be appreciated if you help me for. thanks!!