Thread: Evaluate mathematical expression

  1. #1
    Registered User
    Join Date
    Nov 2011
    Location
    Buea, Cameroon
    Posts
    197

    Evaluate mathematical expression

    i am currently writing a program that is meant to evaluate a mathematical expression of the form a*b-c*d-f . This expression can be of any length and possibly of float variables.

    however, my piece of code is meant to evaluate only about two variables and not more... So i need help with a loop that can evaluate an expression of any length.
    Code:
    //here is my code
    
    
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
         int s;
         char op;
         float exp1, exp2, sum = 0;
         printf ("\nThis program evaluates a mathematical expression of any length.");
          printf("\nEnter 'Q' to exit.");
         
         for ( ; ; )
         {
             printf("\nEnter Expression: ");
            while(getchar() != '\n')
            {
                 s = scanf(" %f %c %f", &exp1,op,exp2);
                  getchar(); // i don't however feel comfortable putting //getchar here... i need help with this loop
                 if ( s != 3)
                 {
                     printf("\nExiting...");
                     exit(EXIT_SUCCESS);
                 }
                 
                 if ( op == '+') sum += exp1 + exp2;
                 else if ( op == '-') sum += exp1 - exp2;
                 else if ( op == '/') sum += exp1 / exp2;
                 else if ( op == '*') sum += exp1 * exp2;
    
               }
               printf("\nExpression: %.2f", sum);
            }
            return 0;
    }
    
    //this code may run only for two expressions and not more....

  2. #2
    Registered User antred's Avatar
    Join Date
    Apr 2012
    Location
    Germany
    Posts
    257
    For complicated expressions that contain any number of sub expressions, I think you'd have to compile the string containing the expressions into an abstract syntax tree. Then once you've done that, evaluate sub expressions from the bottom of the tree up, passing the results into the containing expression until you've reached the root of the tree.

    Abstract syntax tree - Wikipedia, the free encyclopedia

  3. #3
    Registered User
    Join Date
    Nov 2011
    Location
    Buea, Cameroon
    Posts
    197
    yes i agree @antred but i have been explicitely restricted to either use getchar or scanf with loops to solve the problems without using either arrays or trees..... any way i'll check that page on wiki to see what it gives.

  4. #4
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Nyah Check
    i am currently writing a program that is meant to evaluate a mathematical expression of the form a*b-c*d-f . This expression can be of any length and possibly of float variables.
    Hmm... but if you know that the expression is of that form, then you don't need to build an AST because you already know what the AST looks like. It is just a matter of reading the numbers/variables, and checking that the input really is an expression of that form, then computing the result, which is dead simple since you would be reading into 5 variables.

    EDIT:
    Unless you're saying that a, b, c, d and f are not necessarily terminals, in which case you would have not completely stated the syntax of what you intend to parse.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  5. #5
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Are the use of parentheses ( or ) allowed in the input?

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  6. #6
    Registered User
    Join Date
    Nov 2011
    Location
    Buea, Cameroon
    Posts
    197
    however @laserlight the assignment requires that you can evaluate an infinite number of expressions in so far as it is input correctly i think using a while loop can go but however @stahta01 parentheses arenot permitted only the integers of floats with the respective operators.

  7. #7
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Nyah Check
    the assignment requires that you can evaluate an infinite number of expressions in so far as it is input correctly
    What is the exact form, the grammar, of these expressions? For example, consider:
    7 - 2 * 3

    I can evaluate it as (7 - 2) * 3 = 15, or I can evaluate it as 7 - (2 * 3) = 1. The latter interpretation is typical in mathematical notation, and is in fact how it will be evaluated in C. But if you are required to solve this "without using either arrays or trees" and presumably other more complex structures (or by storing into a file, etc), then the latter becomes very hard, maybe even impossible, but computing the former (as in left to right evaluation with the operators having the same precedence) is still pretty easy.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  8. #8
    Registered User
    Join Date
    Nov 2011
    Location
    Buea, Cameroon
    Posts
    197
    however@laserlight. this program uses the first come first some operator style whereby the the expression is evaluated as it is entered, i was thinking of using a while loo p to evaluate the expression using getchar() but this function stores the ascii code and not the integer. so this kinda complicates the expression.

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Nyah Check
    this program uses the first come first some operator style whereby the the expression is evaluated as it is entered
    Okay, so you just evaluate from left to right, with the operators having the same precedence. That's fine.

    Quote Originally Posted by Nyah Check
    i was thinking of using a while loo p to evaluate the expression using getchar() but this function stores the ascii code and not the integer.
    What do you mean by that?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  10. #10
    Registered User
    Join Date
    Nov 2011
    Location
    Buea, Cameroon
    Posts
    197
    @laserlight i think using a variable from getchar() directly on printf gives something different from expected. when i verified i saw getchar stored the ascii code of the variable and not the variable making computation difficult.

  11. #11
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by Nyah Check
    when i verified i saw getchar stored the ascii code of the variable and not the variable making computation difficult.
    Ah. You should subtract '0' to get the value of the numeric character. Furthermore, you should consider how to process a series of digits that form an integer.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  12. #12
    Registered User
    Join Date
    May 2012
    Posts
    1,066
    I don't think using getchar() is the best choice in your case (you have to process floats, haven't you?).
    What's wrong with using scanf()?

    Bye, Andreas

  13. #13
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    Suggest write a function that get the type of operation.

    Simple outline of possible algorithm (untested)

    Code:
    Get first value place it in sum
    Start Loop
      GetOperatorType
      Get Next value
      Do Math Operation
    End Loop
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. [Xcode-Mac OS X] evaluate prefix expression using queues
    By manichandra in forum C Programming
    Replies: 3
    Last Post: 02-29-2012, 04:00 AM
  2. Replies: 17
    Last Post: 10-06-2008, 07:54 PM
  3. How to evaluate a postfix|prefix expression using stack?
    By Marrah_janine in forum C Programming
    Replies: 5
    Last Post: 08-04-2007, 04:12 AM
  4. Help! Program to evaluate expression...
    By Unregistered in forum C++ Programming
    Replies: 7
    Last Post: 02-19-2002, 06:20 AM
  5. Evaluate postfix expression program
    By shad0w in forum C Programming
    Replies: 1
    Last Post: 12-23-2001, 04:40 PM