Thread: Making calculator in C

  1. #1
    Registered User
    Join Date
    Dec 2010
    Posts
    4

    Making calculator in C

    So, I decided to take an independent study Computer science course at my school and my "teacher" assigned me some projects to do (4), which I promised to get them done over Christmas break. I'm currently lost on (project 2) how to make this:

    The following would be a typical input for this program

    7+22-15*23/100^2

    For this assignment parenthesis will not be allowed and will not be tested for. Any illegal character should be ignored and not cause a program error. Decimal points are not allowed in this application, only integers. However, displayed results may be in decimal form (four digits significance).

    I know how to do the basic stuff like have a user input a number, ask if they want to add/sub/div/mult/etc.., then get second number and display results. But I don't know how I would go about getting all the inputs on the same line and have the computer read them (for example, if the user inputs: 7+22-15*23/100^2).

    This is what I have come up with so far, however it does not work:

    Code:
    #include <stdio.h>
    #include <math.h>
    
    int option;
    char q;
    int number;
    int currentsum;
    int value;
    
    void calc()
    {
         printf("\t\t\t\t\tBegin\n"); // says begin in top middle of screen
         option = 0; number = 0; currentsum = 0; value = 0;
         while(1){
                  value = getchar(); // gets user input and sets equal to value
                  if (value >= '0' && value <= '9')
                  {
                     number = number*10 + (value - '0'); /* a way of reading the "values" left to right. If someone puts in 729 as their first number then it will go across
                  and do number = 0*10 (because number was set equal to 0) + 7. then it goes through again. number is now 7 so it goes through and does 7*10 + 2 thus making
                  72. Number is now 72 which means it goes 72*10 + 9 making number 729. It will follow this process if the input is a number 1-9*/
                  }
                  if (value == '+' || value == '-' || value == '*' || value == '/' || value == '^' || value == '=' || value == '\n')
                  {
                       if(value == '+') currentsum = currentsum + number; // if I come across one of these symbols then it performs the operation described
                       if(value == '-') currentsum = currentsum - number;
                       if(value == '*') currentsum = currentsum * number;
                       if(value == '/') currentsum = currentsum / number;
                       if(value == '^') currentsum = pow(currentsum, number);
                       if(value == '=') printf(currentsum);  // when it reads an equal sign or a new line it displays the result of the equation.
                       if(value == '\n') printf(currentsum);
                  }
                  else break; // come across any other symbols or characters break the loop     
                 }
    }
    int main()
    {
        system("title Calculator"); // titles windo "Calculator
        system("color 1A"); // makes background blue
        calc(); // goes to void calc
        system("pause");
        scanf("%c",&q);
        if( q == 'q')exit(0);
    }

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    You appear to be doing things RPN style, which is not what you want. I.e. if you type in
    7+22-15
    you will read the 7, see the + and add the 7, read the 22, see the - and subtract the 22, read the 15, and not have anything to do with it and so ignore it.

    Once you come across a "stopper" (a +, *, a new line, whatever), you need to do the previous operation.

  3. #3
    Registered User krishnapollu's Avatar
    Join Date
    Dec 2010
    Location
    KERALA
    Posts
    29
    hey! i hav done this before!!!

    one way to read the input line of text is like this!!!

    use the getchar() function!!

    compare the input character using ascii value to know whether it is an operand or an operator.

    store the operands and operators in two diff arrays!!
    (store operands as integers ie, 1,2,3etc and operators as the ascii value).

    now do the calculations for the operators with corresponding operands.



    sry that i don hav the code with me now!!!!

    try this!!!

  4. #4
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by krishnapollu View Post
    hey! i hav done this before!!!

    one way to read the input line of text is like this!!!

    use the getchar() function!!

    compare the input character using ascii value to know whether it is an operand or an operator.

    store the operands and operators in two diff arrays!!
    (store operands as integers ie, 1,2,3etc and operators as the ascii value).

    now do the calculations for the operators with corresponding operands.



    sry that i don hav the code with me now!!!!

    try this!!!
    do!!! you!!! really!!!! need!!! all!!! those!!! exclamation!!! marks!!! ?

  5. #5
    Registered User krishnapollu's Avatar
    Join Date
    Dec 2010
    Location
    KERALA
    Posts
    29
    Quote Originally Posted by CommonTater View Post
    do!!! you!!! really!!!! need!!! all!!! those!!! exclamation!!! marks!!! ?
    sry for that. but i hope it wont make any non-sense.

  6. #6
    Registered User
    Join Date
    Dec 2010
    Posts
    4
    Quote Originally Posted by krishnapollu View Post
    hey! i hav done this before!!!

    one way to read the input line of text is like this!!!

    use the getchar() function!!

    compare the input character using ascii value to know whether it is an operand or an operator.

    store the operands and operators in two diff arrays!!
    (store operands as integers ie, 1,2,3etc and operators as the ascii value).

    now do the calculations for the operators with corresponding operands.



    sry that i don hav the code with me now!!!!

    try this!!!
    How do you store ascii values compared to integers?

  7. #7
    Banned ಠ_ಠ's Avatar
    Join Date
    Mar 2009
    Posts
    687
    Quote Originally Posted by HolyTurtle View Post
    How do you store ascii values compared to integers?
    they are stored the same way, his suggestion would be worse than what you're currently doing, as it would lead to magic numbers, but storing them in two different arrays before evaluating them is what you want to do

    your code would look a lot nicer if you use switch statements

    I would also suggest getting rid of your global variables, they are not necessary and it is a very bad programming practice that should be squashed as soon as possible

    currentsum should be of type float, and you'll need to be careful to use floating point division instead of integer division

    If you want your program to respect the order of operations, you will need to completely rework your logic
    Last edited by ಠ_ಠ; 12-29-2010 at 02:53 AM.
    ╔╗╔══╦╗
    ║║║╔╗║║
    ║╚╣╚╝║╚╗
    ╚═╩══╩═╝

  8. #8
    Registered User krishnapollu's Avatar
    Join Date
    Dec 2010
    Location
    KERALA
    Posts
    29
    Quote Originally Posted by HolyTurtle View Post
    How do you store ascii values compared to integers?
    ascii value of 0->48
    and that of 9->57

    so if the read in char falls b/w these values, u can subtract it with 48 and store the reult.
    (eg. if 2 is pressed then ascii value obtained will be 50 and on subtracting it with 48 u will get 2 itself).

    also u need to store the value in a temporary variable
    (the initial value of which shud be 0).
    bcoz for a value greater than 9 u shud perform the following :
    Code:
    temp=(temp*10)+new_value;

  9. #9
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by krishnapollu
    ascii value of 0->48
    and that of 9->57

    so if the read in char falls b/w these values, u can subtract it with 48 and store the reult.
    (eg. if 2 is pressed then ascii value obtained will be 50 and on subtracting it with 48 u will get 2 itself).
    This can work, but as ಠ_ಠ pointed out, you should avoid magic numbers. This can be done by using the isdigit function from <ctype.h> and subtracting '0' rather than 48.
    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 krishnapollu's Avatar
    Join Date
    Dec 2010
    Location
    KERALA
    Posts
    29
    Quote Originally Posted by laserlight View Post
    This can work, but as ಠ_ಠ pointed out, you should avoid magic numbers. This can be done by using the isdigit function from <ctype.h> and subtracting '0' rather than 48.
    oh!
    i really din know about such a function..
    anyway thanks for that..

  11. #11
    Banned
    Join Date
    Aug 2010
    Location
    Ontario Canada
    Posts
    9,547
    Quote Originally Posted by krishnapollu View Post
    sry for that. but i hope it wont make any non-sense.
    While a lot of places on the web don't care much about grammar, this place does. If you think about it, it makes sense... we are talking about a language, afterall. Precision in communication both with our compilers and eachother is an important thing here.

    (With that said: My spelling is probably the worst of anyone here ... LOL )

  12. #12
    Registered User
    Join Date
    Dec 2010
    Posts
    4
    So i've done a little messing arounds..................so can someone tell me why this doesn't work?

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>
    
    int main(int argc, char *argv[])
    {
        int input, number;
        float currentnumber;
    
        while (1)
        {
             input = currentnumber = number = 0;
             while(1)
             {
                  input = getchar();
                  switch(input)
                  {
                       //Handle Numeric values
                       case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
                            number = number*10 + input;
                            break;      
                       //Handle operations
                       case '^':
                           currentnumber = pow(currentnumber,number);
                            break;
                       case '*':
                            currentnumber *= number;
                            break;
                       case '/':
                            currentnumber /= number;
                            break;
                       case '+':
                            currentnumber += number;
                            break;
                       case '-':
                            currentnumber -= number;
                            break;
                       
                       //when "=" or newline output results
                       case '=': case '\n':
                            printf("%f\n", currentnumber);
                            break;
                            
                       //Default handler
                       default:
                               number = 0;
                       break;
                  }                      
             }
        }   
      system("PAUSE");	
      return 0;
    }
    I'm basing this off of my friends code, which does work, that looks like this:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    int main(int argc, char *argv[])
    {
      int c,numcur,num,op,i,temp;
      while (1)
      {
      num=0; /*num is the number currently being determined*/
      numcur=0; /*numcur is the evaluation, up to the most recent operator,
      stored while the calculator determines the number after the operator*/
      op=1; /* so that the first number is added*/
      c=0;
      while (1)
      {
       c=getchar();
       if (c >= '0' && c <= '9') num= num*10 + (c-'0'); /*adds a digit to the end if c is a digit*/
       else if (c == '+' || c == '-' || c == '^' || c == '*' || c == '/' || c == '=' || c == '\n')
       { /*performs the previous operation, then either stores the operator for the next one, or
       breaks from the loop if the next operator is equals or enter*/
            if (op == 1)
            numcur=numcur+num;
            else if (op == 2)
            numcur=numcur-num;
            else if (op == 3)
            { /*my power function*/
                 temp=numcur;
                 for (i=1; i<num; ++i)
                 {
                  numcur=numcur*temp;
                 }
            }
            else if (op == 4)
            numcur=numcur*num;
            else if (op == 5)
            numcur=numcur/num;
            /*now to store the operation*/
            if (c == '+')
            op=1;
            else if (c == '-')
            op=2;
            else if (c == '^')
            op=3;
            else if (c == '*')
            op=4;
            else if (c == '/')
            op=5;
            else break; /*placed after the final assignments so that the last calculation
            is made before the answer is displayed*/
            num=0; /*after completing a calculation, the equation up to the current character
            is evaluated and stored as numcur, and num is the next number to be determined*/
       }
      }
      printf("%d\n\n", numcur); /*displays answer and then skips two lines*/
      } /*infinite loop*/
    }

  13. #13
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Posts
    14,336
    Probably because you destroyed your friend's code, I'm guessing. Did you read the comments that go with it? Let me pull one out:
    Code:
    */performs the previous operation, then either stores the operator for the next one, or
       breaks from the loop if the next operator is equals or enter*/
    Can you honestly say to yourself, "Hey, I tried to do that" and point to a section of your code where you tried to do that?

  14. #14
    Banned ಠ_ಠ's Avatar
    Join Date
    Mar 2009
    Posts
    687
    //Handle Numeric values
    case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9':
    number = number*10 + input;
    break;
    I would like to point out that '0' != 0

    now, ignoring that, lets step through what your program does when it gets the string "1+1="

    currentnumber = 0
    number = 0
    input = 0

    *reads in 1*
    currentnumber = 0
    number = 1
    input = 1

    *reads in '+'*
    currentnumber = 0
    number = 1
    input = '+'

    *adds input to currentnumber*
    currentnumber = 1
    number = 1
    input = '+'

    *reads in 1*
    currentnumber = 1
    number = 11
    input = 1

    *reads in '='*
    currentnumber = 1
    number = 11
    input = '='

    output = "1"


    the next time you encounter a problem and wonder why your program isn't working, try doing what I just did and working out what your program does by hand, it is a fairly common practice and can save you hours of time
    ╔╗╔══╦╗
    ║║║╔╗║║
    ║╚╣╚╝║╚╗
    ╚═╩══╩═╝

  15. #15
    Registered User
    Join Date
    Dec 2010
    Posts
    4
    Quote Originally Posted by tabstop View Post
    Probably because you destroyed your friend's code, I'm guessing. Did you read the comments that go with it? Let me pull one out:
    Code:
    */performs the previous operation, then either stores the operator for the next one, or
       breaks from the loop if the next operator is equals or enter*/
    Can you honestly say to yourself, "Hey, I tried to do that" and point to a section of your code where you tried to do that?
    Bare with my lack of knowledge here, but the part you are talking about is doing the
    "if (c =='+')
    op1;
    etc....."

    and then doing the
    if (op == 1)
    numcur = numcur+num;
    etc...

    If this is not the part you are talking about then I think I'll need you to spell it out for me. Anyways if it is I don't see why you can't just cut out the middle man and have:
    "if ( c== '+')
    numcur = numcur+num;

    I apologize for my stupidity in advance and hope that it is possible that you can explain the reasoning to me in ways that even I can understand.

    Quote Originally Posted by ಠ_ಠ View Post
    I would like to point out that '0' != 0

    now, ignoring that, lets step through what your program does when it gets the string "1+1="

    ......


    output = "1"


    the next time you encounter a problem and wonder why your program isn't working, try doing what I just did and working out what your program does by hand, it is a fairly common practice and can save you hours of time
    If i run the program and put it 1+ 1 I get 49, not 1...
    although I do understand your method of working it out and thank you for it.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Compiling GNU MP
    By mattnp12 in forum C Programming
    Replies: 3
    Last Post: 06-23-2011, 03:58 PM
  2. making sprites
    By DavidP in forum Game Programming
    Replies: 9
    Last Post: 02-20-2010, 07:00 AM
  3. Making great graphics
    By MadCow257 in forum Game Programming
    Replies: 1
    Last Post: 02-20-2006, 11:59 PM
  4. Making control...
    By Finchie_88 in forum C++ Programming
    Replies: 2
    Last Post: 09-07-2004, 01:42 PM
  5. About Unix Programming - Making a career desision
    By null in forum C Programming
    Replies: 0
    Last Post: 10-14-2001, 07:37 AM