Originally Posted by
Salem
So show us what you've got then.
The "I've got some code, but .... " ploy ceased to work long ago.
If you've got a lot of repetitive code, especially if you've been doing ctrl-c and ctrl-v a lot, is "How do I make this into a function?".
As you wish, here is the code:
just some notes:
entering the math equation as string.
I started with loops and while but apparently would the code be more than complexed, I've done with the "+" as the others operator would be the same thing I've done with function "+"..but again would be so long!
Code:
int main()
{
char expr[21];
double ssum=0;
printf("Input ur string:\n");
scanf("%20s",&expr);
ssum = evaluate(expr);
printf("Output: %.2lf", ssum);
return 0;
}
Code:
double evaluate(char expr[])
{
int i=1,j=0;
float e=0,sum=(expr[0]-'0'),temp=0;
while (i<strlen(expr)-1)
{
if(expr[i]=='+')
{
if (expr[i+2]!='\0')
{
temp=(expr[i+1]-'0');
printf("%f",temp);
while (1)
{
temp=temp*10+(expr[i+2]-'0');
i+=1;
if (expr[i]=='+' || expr[i]=='/' || expr[i]=='*'|| expr[i]=='-'||i>=strlen(expr)-2) break;
}
sum+=temp;
}
else
sum+=(expr[i+1]-'0');
}
else if (expr[i]=='-')
sum -= (expr[i+1]-'0' );
else if(expr[i]=='/')
sum=(float)sum/(float)((expr[i+1]-'0'));
else if (expr[i]=='*')
sum *= (expr[i+1]-'0');
else if (expr[i]!='+' || expr[i]!='/' || expr[i]!='*'|| expr[i]!='-' || expr[i]!='\0')
{
sum=sum*10+(expr[i]-'0');
printf("%f",sum);
}
i+=1;
}
return sum;
}
any available clues for another method and shorter one? thanks.