Jump to content

Very Simple C Calculator

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
13 replies to this topic

#1
Guest

Guest

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 3,414 posts
This tutorial is for newbie C programmers. It uses basic skills and makes a useful program.
Things you should know:
how to use scanf and printf
how to use if and while
how to declare variables
know about variable types

First start your C program like normal
#include <stdio.h>


int main()

{
Okay, so what what do you do now? Well, your program needs to accept input for a calculation. For that, we will use the scanf() function. Think of a simple math problem. 1+1. In C programming that is an int, a char, and another int. But wait, what about .2+.5? Those are floating point numbers in C. So the scanf code should look like this:
float num1, num2;

char operation;

scanf("%f%c%f", &num1, &operation, &num2);

Remember: Use the & sign because scanf needs to point to the variable!
This will define two floating point numbers and an operator. Now your program has to compute that. Add this line of code:
if (operation == '+')

printf("%f\n", num1+num2);
Remember: Use == not = when comparing things!
This code says: if char operation equals plus sign then print floating point number num1+num2. Now that you know that, the rest is easy:
if (operation == '-')

printf("%f\n", num1-num2);

if (operation == '*')

printf("%f\n", num1*num2);

if (operation == '/')

printf("%f\n", num1/num2);
We did the same thing, but added subtraction, multiplication, and division.
Now the program does all of that only 1 time. We want to keep entering more problems for the computer to solve. The solution: put the all of the scanf code and the if code into a while loop.
while (1) {

scanf("%f%c%f", &num1, &operation, &num2);

// this is where the rest of the code is

printf("%f\n", num1/num2);

}
We use while (1) because we want to loop forever. As long as the user has math problems, we will keep accepting them until they click X. Now lets finish the program:
return 0;

}
Exit with success. Now we are done! Let's see what all the code looks like at the same time:
#include <stdio.h>


int main()

{

    float num1, num2;

    char operation;

    while (1) {

        scanf("%f%c%f", &num1, &operation, &num2);

        if (operation == '+')

            printf("%f\n", num1+num2);

        if (operation == '-')

            printf("%f\n", num1-num2);

        if (operation == '*')

            printf("%f\n", num1*num2);

        if (operation == '/')

            printf("%f\n", num1/num2);

    }

    return 0;

}
Your code should look like that, if it doesn't, fix your mistakes.
Compile your calculator and try it out! It should work fine, just remember it can only do one calculation at a time.
This calculator is very simple, I will post a more advanced calculator tutorial later if this was too easy.

Edited by Guest, 11 August 2010 - 10:33 AM.

Root Beer == System Administrator's Beer
Download the new operating system programming kit! (some assembly required)

#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
Simple and does the job. +rep :)
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
chili5

chili5

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 7,247 posts
Nice. What if you wanted to expand it to include more operations? How about the value from a previous calculation is used in the next calculation?

#4
Guest

Guest

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 3,414 posts
I will have a more advanced tutorial later that explains all of those things and more.
Root Beer == System Administrator's Beer
Download the new operating system programming kit! (some assembly required)

#5
debtboy

debtboy

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 916 posts
Good Tutorial +rep :)

#6
Guest_Jordan_*

Guest_Jordan_*
  • Guests
Good tutorial, simple and works. +rep

#7
tonymorrison39

tonymorrison39

    Newbie

  • Members
  • PipPip
  • 20 posts
interesting thanks!

#8
heatblazer

heatblazer

    Newbie

  • Members
  • Pip
  • 3 posts
Actually if you want to create a real calc ex. 1+1+2-2+3+3-1-1-1-1-.... etc. You should use a string like if you look at the calculator screen, no more than 12 digits for example, these digits will be chars with atoi() function to get the numerical value of the strings, also you can exclude all chars to be entered by the user except '+' '-' '*' and '\'. I am not 100% sure right now how to do it but coding a real calc is not an easy job, you may want to use a XOR function for exclusive OR which can refer to TRUE when a=1 && b=0 or a=0 or b=1... it`s simple
int xor_demo(int a, int b)
{
return (a || b) && !(a && b); // returns a or b if either is 1(true) or returns FALSE if both are 0=false or both are 1=true
}

#9
Guest

Guest

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 3,414 posts
Yeah, I was going to have a more advanced tutorial, but I never got around to it. You have the right idea with getting string input, but I would avoid atoi() personally. Research the sscanf() function. It's like scanf(), but it takes in a string as input, and it let's you do error checking! strtol() may also be worth checking out.

I may write the bigger and better tutorial after all. If you want, I can send the link to you through PM when it's done.
Root Beer == System Administrator's Beer
Download the new operating system programming kit! (some assembly required)

#10
heatblazer

heatblazer

    Newbie

  • Members
  • Pip
  • 3 posts
Sure thing, always interested in C codes since I am learning more and more! I`ll try to figure out some code too. I know about sscanf. I stuck to atoi() for ints and atof() for floats however there might be many solutions for doing a calc.

#11
Alexander

Alexander

    It's Science!

  • Moderators
  • 4,118 posts
Guest, if you are looking to write a more complex one, you can work with token stacks (Simple calculator), so does longer operations (i.e 2 + 5 * 4). You could also technically utilize YACC/GNU BISON with a lexer for more power:
%{
#define YYSTYPE double
#include <math.h>
%}

/* Declarations */
%token NUM
%left '-' '+'
%left '*' '/'
%left NEG     /* -unary minus */
%right '^'    /* exponentiation        */

/* Grammar rules */
%%
input:    /* empty string */
        | input line
;

line:     '\n'
        | exp '\n'  { printf ("\t%.10g\n", $1); }
;

exp:      NUM                { $$ = $1;         }
        | exp '+' exp        { $$ = $1 + $3;    }
        | exp '-' exp        { $$ = $1 - $3;    }
        | exp '*' exp        { $$ = $1 * $3;    }
        | exp '/' exp        { $$ = $1 / $3;    }
        | '-' exp  %prec NEG { $$ = -$2;        }
        | exp '^' exp        { $$ = pow ($1, $3); }
        | '(' exp ')'        { $$ = $2;         }
;
%%

Edited by Alexander, 03 January 2011 - 06:53 PM.
Links

Be sure to read the updated FAQ! || Health is achieved through the same 10,000 steps.
If a suggested code/method fails, informing us is less important than telling us why or what errors occurred.

#12
Guest

Guest

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 3,414 posts

Alexander said:

Guest, try to write one that parses the string for tokens, and does longer operations (i.e 2 + 5 * 4).
That was the original plan. I'll have it ready in a couple of days, assuming I'm not busy with something else.

I'm not messing with yacc though! I just don't like it, no matter how useful it is.
Root Beer == System Administrator's Beer
Download the new operating system programming kit! (some assembly required)