cpp calculator code example
Example 1: c++ calculator script
#include <iostream>
using namespace std;
int main()
{
cout << "Welcome to the Calculator, write :cancel: to cancel the calculator\n";
string cancel;
while(cancel != "cancel")
{
int number1 = 0;
int number2 = 0;
string op;
cout << "please enter your first number!\n";
cin >> number1;
cout << "please enter your second number!\n";
cin >> number2;
cout << "please enter a operator!\n";
cout << "( *, / , + , - )";
cin >> op;
if(op == "*")
{
number1 = number1 * number2;
cout << number1;
number1 = 0;
number2 = 0;
}
if(op == "/")
{
number1 = number1 / number2;
cout << number1;
number1 = 0;
number2 = 0;
}
if(op == "+")
{
number1 = number1 + number2;
cout << number1;
number1 = 0;
number2 = 0;
}
if(op == "-")
{
number1 = number1 - number2;
cout << number1;
number1 = 0;
number2 = 0;
}
cout << "Write cancel to cancel\n";
cout << "write continue to resume with the calculator!\n";
cin >> cancel;
}
}
Example 2: calculator with c++
#include <iostream>
using namespace std;
int main()
{
int choice;
cout << 1 << endl;
cout << 2 << endl;
cout << 3 << endl;
cout << 4 << endl;
cout << "Choice A Number: ";
cin >> choice;
if (choice >= 1 && choice <= 4)
{
int a, b;
cout << "Enter Num One: ";
cin >> a;
cout << "Enter Num Two: ";
cin >> b;
if (choice == 1)
cout << a << "+" << b << "=" << a + b << endl;
if (choice == 2)
cout << a << "-" << b << "=" << a - b << endl;
if (choice == 3)
cout << a << "*" << b << "=" << a * b << endl;
}
else
{
cout << "Wrong Choice" << endl;
}
}
Example 3: c++ calculator
#include <iostream>
using namespace std;
int main() {
char setOperator;
float firstNum = 0.00, secondNum = 0.00;
cout << "Enter your operater: +, -, *, /: \n";
cin >> setOperator;
cout << "Enter your first calculation: \n";
cin >> firstNum;
cout << "Enter your second calculation: \n";
cin >> secondNum;
switch(setOperator) {
case '+':
cout << "The answer is: " <<firstNum + secondNum;
break;
case '-':
cout << "The answer is:" << firstNum - secondNum;
break;
case '*':
cout << "The answer is: " << firstNum * secondNum;
break;
case '/':
cout << "The answer is: " << firstNum / secondNum;
break;
}
return 0;
}