Thread: Calculator in C?

  1. #1
    Registered User
    Join Date
    Aug 2003
    Posts
    11

    Calculator in C?

    Hi,

    I'm new to this site, and new to programming in C. I'm doing the Sam's 21 day tutorial, and had a problem making a calculator. I made one that will add, subtract, multiply, and divide 2 numbers, but i would like to be able to add multiple numbers. The section I'm studying is about making menus, using break statements, and infinate loops. So, I'm not asking anyone to write me code for a calculator, but If anyone has, could I please see the code? It's no big deal, but I would like to see how it would really be written. I'll post my sad attempt just for fun!

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    
    void delay(void);
    int menu(void);
    float sum(float, float);
    float sub(float, float);
    float product(float, float);
    float quotient(float, float);
    float x;
    float y;
    
    main()
    
    
    
    {
          while (1)
    	{
    			
    	   switch(menu())
    	      {
    		case 1:
    		        {
    			puts("Enter two numbers to add:");
                            sum(x, y);
    		        break;
    			}
    
    	        case 2:
    			{
    		        puts("Enter two numbers to subtract:");
    			sub(x, y);
    			break;
    			}
    	        case 3:
    			{
    			puts("Enter two numbers to multiply:");
    			product(x, y);
    			break;
    			}
    
                    case 4:
    			{
    			puts("Enter two numbers to divide:");
    			quotient(x, y);
    			break;
    			}
                    case 5:
    			{
    			puts("Exiting program now...");
    			exit(0);
                            }
    			default:
    			{
    			puts("\nInvalid choice, try again.");
    			}
    
                        }
    
    			
                }
    }      				
    				
    
    
    
    float sub(float x, float y)
    {
            printf("\nEnter your first number:");
           	scanf("%f", &x);
    	printf("\nEnter your second number:");
    	scanf("%f", &y);
    	printf("\nThe result is: %.2f\n\n", x - y);
    
            return x - y;
    }
    
    float product(float x, float y)
    {               
    
            printf("\nEnter your first number:");
    	scanf("%f", &x);
    	printf("\nEnter your second number:");
    	scanf("%f", &y);
    	printf("\nThe result is: %.2f\n\n", x * y);
    
            return (x * y);
    }
    float quotient( float x, float y)
    {
            printf("\nEnter your first number:");
    	scanf("%f", &x);
    	printf("\nEnter your second number:");
    	scanf("%f", &y);
    	printf("\nThe result is: %.2f\n\n", x/y);
    
            return x/y;
    }
    
    float sum(float x, float y)
    {              
    
            printf("\nEnter your first number:");
    	scanf("%f", &x);
    	printf("\nEnter your second number:");
    	scanf("%f", &y);
    	printf("\nThe result is: %.2f\n\n", x + y);	
    	return x + y;
    }
    
    
    int menu(void)
    
    
    {
    
    int reply;
    
    	puts("Enter 1 for addition:");
    	puts("Enter 2 for subtraction:");
    	puts("Enter 3 for multiplication:");
    	puts("Enter 4 for division:");
    	puts("Enter 5 to exit:");
    
    	scanf("%d", &reply);
    
    	return reply;
    }

  2. #2
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,164
    Dave,
    One thing you need to be aware of is the format of the funtion call for main. It is
    int main()
    Many compilers will give you an error if you use
    main()
    void main()

    I realize the SAMs book probably uses the form you used, but it is wrong.

    Also, once you get the program working the way you like it, try this as an additional exercise:

    Notice each of your math functions ask for two numbers. Pull those out and let the math function do only the math.
    Read the numbers before or after your menu. This will probably be easier to carry the total from one function to the other.

    To use the last total, figure out a way to use the input of the numbers to flag that one number was entered and use the total from the last calculation as the first or second number.
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

  3. #3
    Registered User VirtualAce's Avatar
    Join Date
    Aug 2001
    Posts
    9,607
    The best way to implement a calculator is to use a stack. Create a stack in memory via a linear array. Your stack size does not need to be that large. Then decide on 'opcodes' in your stack to encode the desired operations.

    For instance:


    EQUALS
    ADD 10
    SUB 15
    MUL 3
    PUSH 7

    This stack would do (7*3)-15+10=.

    You use the result from the last operation as the operand for the next one. There is more, but you should be able to do some fairly complex operations via a stack. There are several methods for creating a calculator and this one might be a bit too complex for you, but you can try something like it.

    Here are some general stack operations.

    PUSH - pushes a value onto the stack
    POP - pops or takes a value off of the stack, changes the current stack pointer - stack pointer points to current opcode on the stack.

    You can synthesize new operations for the stack for your calculator and really the sky is the limit.

  4. #4
    Registered User
    Join Date
    Aug 2003
    Posts
    11
    Thanks for the replies.

    I didn't even realize I did that with the main(). I use the borland compiler and it let it pass, but I will take your advice and put in the int main() next time. I tried taking the numbers outside the functions and couldnt seem to get it to work. I'll keep trying. I know what I want it to do, just can't make it happen.
    Bubba, that is a little too advanced for me at this point, but I appreciate the reply. I've gotten into array's, but not stacks and pushes.

  5. #5
    Registered User
    Join Date
    Aug 2003
    Posts
    11
    I know I'm jumping way ahead of myself here, but I am a bit curious about GUI. How do you make nice program window, or GUI's for C programs? As opposed to the dos windowns i see now. Will I have to learn visual basic to do this?

  6. #6
    Been here, done that.
    Join Date
    May 2003
    Posts
    1,164
    You just need to find an editor that color-codes C programs and can send a compile command to Windows. I use VEdit which can do that (although I don't use the compile & run feature). I'm sure there are many other editors that allow this functionality.

    I tried taking the numbers outside the functions and couldnt seem to get it to work.
    Did you realize the calling parameters of each function must change too? I suspect that may be a factor.
    Edit...
    I just looked at your original post and my comment is in error. Without looking since you read the values within the function I assumed you didn't pass parameters. It should be a very simple matter to remove the inputs from each function the way you have it written.
    Last edited by WaltP; 08-04-2003 at 10:40 AM.
    Definition: Politics -- Latin, from
    poly meaning many and
    tics meaning blood sucking parasites
    -- Tom Smothers

Popular pages Recent additions subscribe to a feed