Mike
2012-03-13 20:06:26 UTC
Computer-> Please Enter a new Sequence:
User-> 34+
Computer-> (3) + (4) = (7)
Computer-> Please Enter a new Sequence:
but my output is:
Computer-> Please Enter a new Sequence:
User-> 34+
Computer-> (3) + (4) = (7)
Computer-> Please Enter a new Sequence:
Computer-> (3) + (4) = (7)
Computer-> Please Enter a new Sequence:
The output repeats.
#include
#include
void evaluate(int line[]);
main()
{
int line[3];
while (1) /* runs continually unless '#' is entered */
{
int c, i;
printf("Please enter a new sequence: \n");
for (i = 0; i < 3 && (c = getchar()) && c != '\n'; i++) /* loop initializes the array with two digits and an operator */
{
if (c == '#') /* no more sequences */
break;
else
line[i] = c;
}
if (c == '#')
break;
evaluate(line); /* function call */
}
printf("Good bye!\n");
}
void evaluate (int line[]) /* evaluates and displays the answer to the postfix expression */
{
int firstOp, secondOp, answer;
switch (line[0]) /* makes sure there is a number, assigns it to the local variable */
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
firstOp = line[0] - 48; /* turns the ascii value for the int into an int value */
break;
default:
printf("Not an integer\n");
break;
}
switch (line[1]) /* makes sure there is a number, assigns it to the local variable */
{
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
secondOp = line[1] - 48; /* turns the ascii value for the int into an int value */
break;
default:
printf("Not an integer\n");
break;
}
switch (line[2]) /* makes sure there is an operator, then computes the sum/difference/product/quotient */
{
case '+':
answer = firstOp + secondOp;
break;
case '-':
answer = firstOp - secondOp;
break;
case '*':
answer = firstOp * secondOp;
break;
case '/':
answer = firstOp / secondOp;
break;
default:
printf("Illegal operator\n");
break;
}
printf("(%d) %c (%d) = (%d)\n", firstOp, line[2], secondOp, answer); /* displays the sum */
}