Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
* * * * - 1 votes

Very Simple C Calculator

calculator variable type

  • Please log in to reply
15 replies to this topic

#1 Guest

Guest

    CC Devotee

  • Expert Member
  • PipPipPipPipPipPip
  • 914 posts
  • Location:USA
  • Programming Language:C, Java, Python, Bash, Others
  • Learning:Assembly, Scheme

Posted 27 September 2009 - 01:40 AM

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.

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

#2 WingedPanther73

WingedPanther73

    A spammer's worst nightmare

  • Moderator
  • 17757 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others

Posted 27 September 2009 - 11:33 AM

Simple and does the job. +rep :)
  • 0

Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

My MineCraft server site: http://banishedwings.enjin.com/


#3 chili5

chili5

    CC Mentor

  • Expert Member
  • PipPipPipPipPipPipPipPip
  • 3038 posts
  • Programming Language:Java, C#, PHP, JavaScript, Ruby, Transact-SQL
  • Learning:C, Java, C++, C#, PHP, JavaScript, Ruby, Transact-SQL, Assembly, Scheme, Haskell, Others

Posted 27 September 2009 - 03:44 PM

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?
  • 0

#4 Guest

Guest

    CC Devotee

  • Expert Member
  • PipPipPipPipPipPip
  • 914 posts
  • Location:USA
  • Programming Language:C, Java, Python, Bash, Others
  • Learning:Assembly, Scheme

Posted 27 September 2009 - 07:22 PM

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

#5 debtboy

debtboy

    CC Devotee

  • Just Joined
  • PipPipPipPipPipPip
  • 499 posts

Posted 28 September 2009 - 02:54 PM

Good Tutorial +rep :)
  • 0

#6 Guest_Jordan_*

Guest_Jordan_*
  • Guest

Posted 05 October 2009 - 06:16 AM

Good tutorial, simple and works. +rep
  • 0

#7 tonymorrison39

tonymorrison39

    CC Newcomer

  • Just Joined
  • PipPip
  • 20 posts

Posted 21 November 2009 - 08:54 AM

interesting thanks!
  • 0

#8 heatblazer

heatblazer

    CC Lurker

  • Just Joined
  • Pip
  • 3 posts

Posted 03 January 2011 - 07:01 AM

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
}
  • 0

#9 Guest

Guest

    CC Devotee

  • Expert Member
  • PipPipPipPipPipPip
  • 914 posts
  • Location:USA
  • Programming Language:C, Java, Python, Bash, Others
  • Learning:Assembly, Scheme

Posted 03 January 2011 - 07:50 AM

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.
  • 0
Root Beer == System Administrator's Beer
Download the new operating system programming kit! (some assembly required)

#10 heatblazer

heatblazer

    CC Lurker

  • Just Joined
  • Pip
  • 3 posts

Posted 03 January 2011 - 09:05 AM

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.
  • 0

#11 Alexander

Alexander

    YOL9

  • Moderator
  • 3963 posts
  • Location:Vancouver, Eh! Cleverness: 200
  • Programming Language:C, C++, PHP, Assembly

Posted 03 January 2011 - 06:46 PM

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

  • 0

All new problems require investigation, and so if errors are problems, try to learn as much as you can and report back.


#12 Guest

Guest

    CC Devotee

  • Expert Member
  • PipPipPipPipPipPip
  • 914 posts
  • Location:USA
  • Programming Language:C, Java, Python, Bash, Others
  • Learning:Assembly, Scheme

Posted 03 January 2011 - 06:55 PM

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.
  • 0
Root Beer == System Administrator's Beer
Download the new operating system programming kit! (some assembly required)





Also tagged with one or more of these keywords: calculator, variable type