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.