Home > Back-end >  Print the correct expression and the operator in the final output
Print the correct expression and the operator in the final output

Time:02-15

  #include<stdio.h>
int main()
{
      float value1[3]; 
      float value2[3];
      char operator[3];
      char * opstr;

      float results[3] = {0};
      
    for(int i=0;i<3;i  ){
      printf("Type in your expression. \n");
      scanf ("%f %c %f",&value1[i],&operator[i],&value2[i]);
      switch(operator[i]) 
      {
        case ' ':
          results[i] = value1[i]   value2[i];
          opstr = "plus";
          break;
        case '-':
          results[i] = value1[i] - value2[i];
          opstr = "minus";
          break;
        case '*':
          results[i] = value1[i] * value2[i];
          opstr = "times";
          break;
        case '/':
          results[i] = value1[i] / value2[i];
          opstr = "divided by";
          break;
        default:
          printf("Unknown Operator \n");
          return 0;
        }
     }
     for(int i = 0;i<3;i  ){
          printf("Result of %.2f %s %.2f is : %.2f\n", value1[i], opstr, value2[i], results[i]);
     }

}

This C program has the user enter 3 expressions and the program will return an answer. The problem is that the output looks something like this:

Type in your expression: 3 2

Type in your expression: 3*6

Type in your expression: 1 4

Result of 1 4 is: 5

Result of 1 4 is: 18

Result of 1 4 is: 5

Where the result of the expression is correct, but it doesn't print the correct expression at the end. It only prints the more recent expression (1 4).

My question is how do I print the correct expression and the operator in the final result as a string(plus, minus, divided by, etc) to look more like this:

Type in your expression: 3 2

Type in your expression: 3*6

Type in your expression: 1 4

Result of 3 plus 2 is: 5

Result of 3 times 6 is: 18

Result of 1 plus 4 is: 5

CodePudding user response:

you need 3 arrays

one for the left arguments, one for the operations and one for the right arguments.

  float lefts[3], 
  float rights[3];
  char operators[3];
  float results[3] = {0};
  ....

then in the loop

     scanf ("%f %c %f",&lefts[i],&operators[i],&rights[i]);

CodePudding user response:

the simple way is

  char * opstr;
  switch(operator[i]){
     case ' ':
      opstr = "plus";
      break;
    case '-':
      opstr = "minus";
      break
 ....
  }

  
 

and printf opstr as %s

  • Related