If anyone is up all bright and early, I'm working on an assignment (a glorified calculator it seems).
For part 1 of the assignment I had to write the main program that called my eval_expr function. Got it working great.
Part 2 of my homework modifies the eval function to handle arithmetic expressions within ( ). Spec says to modify while loop into a do-while giving the following example:
do
{
if (scanf("%lf", &num) != 1)
{ /*if num*/
if (scanf(" %c", &op) == 1 && op =='(' ) /* if '(' */
num = eval_expr(); /* call expr using recursion */
}
...
} while (op && op != ';' && op != ')' );
with the assumption that we figure out what goes in the ... section.
The following is my code from part 1:
#include <stdio.h>
#define True 1
#define False 0
double eval_expr(void); /*function that will evaluate user's expression*/
int
main (void)
{
double value;
printf("Enter an arithmetic expression: ");
value = eval_expr();
printf("The value of the expression is: %lG ", value);
return 0;
}
double eval_expr(void) /*evaluate user's expression*/
{
double num, term, exp= 0.0; /*temporary operands*/
char op, aop = 0, mop= 0; /*temporary operators*/
while (scanf("%lf", &num) ==1) /*get next operand*/
{
if (mop == '*') /*process multi op*/
term *= num;
else if (mop == '/')
term /= num;
else
term = num;
mop = 0; /*reset mult op*/
if (scanf(" %c", &op) != 1) /*get next operator*/
op = 0;
if (op == '*' || op == '/') /*set next multi op*/
{
mop = op;
continue;
}
if (aop == '+') /*process add op*/
exp += term;
else if (aop == '-')
exp -= term;
else
exp = term;
aop = 0; /*reset add op*/
if (op == '+' || op == '-') /*set next add op*/
{
aop = op;
continue;
}
if (op == 0 || op == ';')
break; /*end at EOF or semicolon*/
}
return exp;
}
I modifyed my code above to add:
do loop before the above original while loop, and it's companion while after the orig while loop but before return exp. (as the spec example shows)
it compiles/builds correctly, but running the program and entering the following expression:
(1+2)*3;
it returns a value of 3
I'm thinking that it is now only doing the arithmetic within( ) and ending the do-while loop (thus the inner while loop).
I've tried making several types of changes and neither myself or classmates can figure what we need to do. Either I get incorrect math results, or program will hang after user input.
help!
Can't move on to the next part (call the function in another .c file) until I get this corrected.
--Mel, thanks in advance