Write a C program sentencec that takes a math expression eva

Write a C program sentence.c that takes a math expression, evaluates it from left to right, and prints the expression as text and result as type double with 2-digit precision. The input operands in the expressions will always be single-digit non-negative integers and the operators will be +, -, *, or /. Ignore any other characters such as parentheses, braces or brackets, and evaluate the expression from left to right regardless of any mathematical order of operations.

Solution

// C code evaluate expression strict left to right

#include <stdio.h>
#include <stdlib.h>
int main()
{
   char *buffer;
    size_t bufsize = 256;
    size_t characters;
    char operator;
    int i,op1=1,op2=0,operand1,operand2;
    double op = 0.0;

    buffer = (char *)malloc(bufsize * sizeof(char));
    if( buffer == NULL)
    {
        perror(\"Unable to allocate buffer\");
        exit(1);
    }

    printf(\"Enter the expression: \");
    characters = getline(&buffer,&bufsize,stdin);
    for(i=0;i<characters;i++)
    {
      
       if(buffer[i]>=\'0\'&&buffer[i]<=\'9\'&&op1==1)
       {
             
           operand1=buffer[i]-\'0\';
           op=operand1;
           op1=0;
           op2=1;
       }
       else if(buffer[i]>=\'0\'&&buffer[i]<=\'9\'&&op2==1)
       {
           operand2=(int)buffer[i]-\'0\';

           if(operator==\'+\')
           {
               op=op+operand2;
           }
           else if(operator==\'-\')
           {
               op=op-operand2;

           }
           else if(operator==\'*\')
           {
               op=op*operand2;

           }

           else if(operator==\'/\')
           {
               op=op/operand2;

           }
           op1=0;
           op2=1;
       }
       else if(buffer[i]==\'+\'||buffer[i]==\'-\'||buffer[i]==\'*\'||buffer[i]==\'/\')
       {
          
           operator=buffer[i];
       }
    }
    printf(\"result = %.2lf\ \",op);
   return 0;
}


/*
output:

Enter the expression: 9/2+(2*2)
result = 13.00


Enter the expression: (2-3)*4
result = -4.00


*/

Write a C program sentence.c that takes a math expression, evaluates it from left to right, and prints the expression as text and result as type double with 2-d
Write a C program sentence.c that takes a math expression, evaluates it from left to right, and prints the expression as text and result as type double with 2-d

Get Help Now

Submit a Take Down Notice

Tutor
Tutor: Dr Jack
Most rated tutor on our site