How to make an calculator in C++
The source code bellow is the simple sample calculator in cpp, c++ or c. This will serve as tutorial for the beginners who want to learn c language. This simple calculator that I make, allows the user to inputs 2(two) numbers and choose an operation to be used.
Instead of using symbols such as +(add), -(minus), *(multiply) and /(divide), I use letter to represent a single operation.
- This are the following letter that I used:
- A = Addition
- S = Subtraction
- M = Multiplication
- D = Division
If the user input another letter that does not include to the choices, 'invalid operation' will show.
Basic knowledge
If else statement, declaring variables, data types, printf, scanf,
- Advantage
- It can compute number with decimal point.
- Easy to use and understand.
- It shows the complete answer together with the user’s input.
- Disadvantage
- Only 2 numbers are allow to input.
- It can’t perform multiple operations at a time.
- Decimal point always shows (because I use float data type)
*My Compiler is turbo c.
The calculator source code in c++,c or cpp
#include<stdio.h>
#include<conio.h>
#include<ctype.h>
#define p printf
#define s scanf
main()
{
float fnum,snum,ans;
char operation, ope;
clrscr();
p("Simple Calculator \n A=adddition, S=subtraction, M=multiplication, D=division\n");
p("First number:");
s("%f",&fnum);
p("Operation:");
operation=getche();
operation=toupper(operation);
p("\nSecond Number:");
s("%f",&snum);
if(operation=='A'){
ope='+';
ans=fnum+snum;}
else if (operation=='S'){
ope='-';
ans=fnum-snum;}
else if (operation=='M'){
ope='x';
ans=fnum*snum;}
else if (operation=='D'){
ope='/';
ans=fnum/snum;}
else p("Invalid Operation!");
p("%f %c %f the Answer is %f",fnum, ope, snum, ans);
getch();
}
I hope you like my tutorial in making an easy and simple calculator in C, C++ or CPP. So for the beginners (like me) out there, what are you waiting for try it now!
I think you forgot the modulo(%) operation
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteThank's for send it.
ReplyDelete