Thread: Four function calculator assignment.

  1. #1
    Registered User
    Join Date
    May 2015
    Posts
    130

    Four function calculator assignment.

    Hello, I'm wondering what's the best way to start for coding a code that evaluate a math string equating with operator "+-/*", I thought in a recursion but its apparently sounds impossible!! any clues for please? thanks in advance, btw by loops already done but the code so long, so must be another shorter method for evaluating.

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    We are not a homework service. Even if we were, you have provided 0 requirements. Would the homework be reimplementing the windows calculator? Is it a console program? If it is a console program, how is the input received? Is it like this?
    Code:
    perl -e "print 45 + 60 - 80 + 90"
    115
    All of these things are unclear.

    The big problem is that you have yet to post code in either of your threads. We can help you with specific issues, but things like the above are why it is important for you to make an attempt, and to demonstrate what the output should be. It's your homework. You need to be able to hand in something you understand.

  3. #3
    Registered User
    Join Date
    May 2015
    Posts
    130
    Quote Originally Posted by whiteflags View Post
    We are not a homework service. Even if we were, you have provided 0 requirements. Would the homework be reimplementing the windows calculator? Is it a console program? If it is a console program, how is the input received? Is it like this?
    Code:
    perl -e "print 45 + 60 - 80 + 90"
    115
    All of these things are unclear.

    The big problem is that you have yet to post code in either of your threads. We can help you with specific issues, but things like the above are why it is important for you to make an attempt, and to demonstrate what the output should be. It's your homework. You need to be able to hand in something you understand.
    Lol I already told you that I succeeded in coding this problem by a loops methods but its so long..and I have no idea if there's another shorter way for scripting that's why I didn't post any code in this thread!! If a Op hasnt any clue of any method to code his code how would he gets started as u asduming? U people are realy weird; anyway thanks for ur help.

  4. #4
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,743
    So show us what you've got then.

    The "I've got some code, but .... " ploy ceased to work long ago.

    If you've got a lot of repetitive code, especially if you've been doing ctrl-c and ctrl-v a lot, is "How do I make this into a function?".
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  5. #5
    Registered User
    Join Date
    May 2015
    Posts
    130
    Quote Originally Posted by Salem View Post
    So show us what you've got then.

    The "I've got some code, but .... " ploy ceased to work long ago.

    If you've got a lot of repetitive code, especially if you've been doing ctrl-c and ctrl-v a lot, is "How do I make this into a function?".
    As you wish, here is the code:
    just some notes:
    entering the math equation as string.
    I started with loops and while but apparently would the code be more than complexed, I've done with the "+" as the others operator would be the same thing I've done with function "+"..but again would be so long!

    Code:
    int main()
    {
       char expr[21];
       double ssum=0;
       printf("Input ur string:\n");
       scanf("%20s",&expr);
       ssum = evaluate(expr);
       printf("Output: %.2lf", ssum);
       return 0;
    }
    Code:
    double evaluate(char expr[])
    {
        int i=1,j=0;
        float e=0,sum=(expr[0]-'0'),temp=0;
        while (i<strlen(expr)-1)
        {
            if(expr[i]=='+')
            {
                if (expr[i+2]!='\0')
                {
                    temp=(expr[i+1]-'0');
                    printf("%f",temp);
                    while (1)
                    {
                    temp=temp*10+(expr[i+2]-'0');
                    i+=1;
                    if (expr[i]=='+' || expr[i]=='/' || expr[i]=='*'|| expr[i]=='-'||i>=strlen(expr)-2) break;
                    }
                sum+=temp;
                }
                else
                    sum+=(expr[i+1]-'0'); 
            }
            else if (expr[i]=='-')
                sum -= (expr[i+1]-'0' );
            else if(expr[i]=='/')
                sum=(float)sum/(float)((expr[i+1]-'0'));
            else if (expr[i]=='*')
                sum *= (expr[i+1]-'0');
            else if (expr[i]!='+' || expr[i]!='/' || expr[i]!='*'|| expr[i]!='-' || expr[i]!='\0')
            {
                sum=sum*10+(expr[i]-'0');
                printf("%f",sum);
                }
            i+=1;
        }
        return sum;
    }

    any available clues for another method and shorter one? thanks.

  6. #6
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,550
    I suggested this to another user recently, but since it also applies here, I suggest that you:

    1. Parse the input string into tokens.
    2. Implement the Shunting Yard algorithm to convert from infix form to postfix (reverse Polish) form.
    3. Evaluate the expression in postfix form.

    #1 and #2 can be combined. Back as an undergraduate, I pretty much implemented the same thing using the Wikipedia articles on the Shunting Yard algorithm and reverse polish notation for reference.

    I do not know if the end result for you will be shorter than your previous attempt, but I do know that this is a structured way of doing it such that you can extend it quite nicely beyond the four functions specified.
    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

  7. #7
    Registered User
    Join Date
    May 2015
    Posts
    130
    Quote Originally Posted by laserlight View Post
    I suggested this to another user recently, but since it also applies here, I suggest that you:

    1. Parse the input string into tokens.
    2. Implement the Shunting Yard algorithm to convert from infix form to postfix (reverse Polish) form.
    3. Evaluate the expression in postfix form.

    #1 and #2 can be combined. Back as an undergraduate, I pretty much implemented the same thing using the Wikipedia articles on the Shunting Yard algorithm and reverse polish notation for reference.

    I do not know if the end result for you will be shorter than your previous attempt, but I do know that this is a structured way of doing it such that you can extend it quite nicely beyond the four functions specified.
    I got you exactly!, the previous way seemed for me as something very very complexed but it would be worked, I thought like that because when a programmer found himself using many condition if and elseif for a code that would really not deserve that much rows's script then the programmer isn't in the proper way.. .

    and may you hint or actually instruct me how to insert into tokens? I know there's a function called strstrok() but the case is how to split the string for every arrive to operators (+ - * /), that's my whole problem, and else would be more easily for me.(parsing from str to int or float I've the idea of..)
    thanks.

  8. #8
    Registered User
    Join Date
    May 2015
    Posts
    130
    I got the idea how to insert into token, thanks anyway.

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    27,550
    Quote Originally Posted by Romyo2
    and may you hint or actually instruct me how to insert into tokens? I know there's a function called strstrok() but the case is how to split the string for every arrive to operators (+ - * /), that's my whole problem, and else would be more easily for me.(parsing from str to int or float I've the idea of..)
    strtok works well if you have delimiters, e.g., "45 + 60 - 80 + 90" could be easily parsed with strtok by splitting at the spaces. But if you have to cater to say, "45+60-80+90", strtok is probably not the right tool for the job. I see that you have another thread concerning this though: splitting a string.
    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
    May 2015
    Posts
    130
    Quote Originally Posted by laserlight View Post
    strtok works well if you have delimiters, e.g., "45 + 60 - 80 + 90" could be easily parsed with strtok by splitting at the spaces. But if you have to cater to say, "45+60-80+90", strtok is probably not the right tool for the job. I see that you have another thread concerning this though: splitting a string.
    Yes , just got an answer in this thread recently...thank you very much.

  11. #11
    Registered User
    Join Date
    May 2015
    Posts
    130
    Quote Originally Posted by laserlight View Post
    I suggested this to another user recently, but since it also applies here, I suggest that you:

    1. Parse the input string into tokens.
    2. Implement the Shunting Yard algorithm to convert from infix form to postfix (reverse Polish) form.
    3. Evaluate the expression in postfix form.

    #1 and #2 can be combined. Back as an undergraduate, I pretty much implemented the same thing using the Wikipedia articles on the Shunting Yard algorithm and reverse polish notation for reference.

    I do not know if the end result for you will be shorter than your previous attempt, but I do know that this is a structured way of doing it such that you can extend it quite nicely beyond the four functions specified.
    Well, I'm still beginning to learn C so please bear as much as you can with me, I've created this code as following as what you've instructed me like splitting and input into tokens..etc..(btw haven't succeeded to do every step that you given above), when I compile the code it works fine but the giving wrong result, specifically he does that when there's a transmission from operator to another, e.g if i put in the string input just "+"'s operator it gives a correct answer but if I add in the same time another operator like "4-5+6" it gives a wrong answer!!, it doesn't show any errors, I dont know how to deal with this, please help me so , here is my code
    Code:
    #include <stdio.h>
    #include <string.h>
    
    
    int main ()
    {
        char n='r';
        char str[] ="33+4";
        int i=0,l=0;
        int sum=0;
      char * pch;
      while (i<strlen(str))
      {
          n='r';
          i+=1;
          if (str[i]=='/' || str[i]=='+'|| str[i]=='-'||str[i]=='*') break;
      }
      n=str[i];
      printf ("Splitting string \"%s\" into tokens:\n",str);
      pch = strtok (str,"+-/*");
      sum=atoi(pch);;
      printf("%f",sum);
         while (pch != NULL)
        {
            if (n=='+')
            {
                pch = strtok (NULL, "+-/*");
                sum+=(atoi(pch));
                printf("%d",sum);
            }
            else
            {
                pch = strtok (NULL, "+-/*");
                l=strlen(pch);
                n=str[l+1];
            }
    if (n=='-')        {
                printf("hihi");
                if (sum>0)
                {
                    sum=sum-atoi(pch);
                    pch = strtok (NULL, "+-/*");
                }
                else
                {
                    sum=sum-atoi(pch);
                    pch = strtok (NULL, "+-/*");
                }
    //the operator * and / I would have done them in the same thing I've done with previous operators (+-) but the previous operators codes aren't working correctly so I just kept the left operators away until I succeed in the previous operators(+-)//
            }
    
         }
        return 0;
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. BMI calculator part #2 with added function
    By jaaaaaamie in forum C Programming
    Replies: 2
    Last Post: 08-17-2013, 03:38 PM
  2. Loan Calculator (problem with function & pointer)
    By naspek in forum C Programming
    Replies: 15
    Last Post: 09-01-2009, 12:42 PM
  3. function pointer calculator
    By bertazoid in forum C Programming
    Replies: 3
    Last Post: 02-20-2009, 09:12 AM
  4. Replies: 6
    Last Post: 05-11-2007, 01:13 AM
  5. Replies: 2
    Last Post: 05-10-2002, 04:16 PM