how to implement a calculator c++ code example
Example 1: how to make a calculator inc++
#include <iostream>
using namespace std;
int main() {
cout << "Please enter the first number: ";
double n1 = 0;
cin >> n1;
cout << "Please enter an operator (+, -, *, /): ";
char op = '0';
cin >> op;
cout << "Please enter a second number: ";
double n2 = 0;
cin >> n2;
double answer = 0;
switch (op) {
case '+':
answer = n1 + n2;
break;
case '-':
answer = n1 - n2;
break;
case '*':
answer = n1 * n2;
break;
case '/':
answer = n1 / n2;
break;
}
cout << "Thanks for using my calculator your answer is: " << answer;
#include <iostream>
#include <Windows.h>
using namespace std;
int main() {
char jim = 'j';
do {
cout << "Please enter the first number: ";
double n1 = 0;
cin >> n1;
cout << "Please enter an operator (+, -, *, /): ";
char op = '0';
cin >> op;
cout << "Please enter a second number: ";
double n2 = 0;
cin >> n2;
double answer = 0;
switch (op) {
case '+':
answer = n1 + n2;
break;
case '-':
answer = n1 - n2;
break;
case '*':
answer = n1 * n2;
break;
case '/':
answer = n1 / n2;
break;
}
cout << "Thanks for using my calculator your answer is: " << answer << " do you want to run the program again? (y or n) ";
cin >> jim;
} while (jim = 'y' && jim != 'n');
if (jim = 'n') {
cout << "Thanks for using my calculator here is sum epic music";
Beep(329, 300);
Beep(493, 300);
Beep(698, 300);
Beep(659, 600);
Beep(783, 300);
Beep(698, 300);
Beep(659, 600);
Beep(329, 100);
Beep(493, 300);
Beep(698, 300);
Beep(659, 600);
Beep(392, 250);
Beep(440, 200);
Beep(587, 300);
Beep(349, 250);
Beep(587, 500);
Beep(329, 300);
Beep(493, 300);
Beep(698, 300);
Beep(659, 600);
Beep(783, 300);
Beep(698, 300);
Beep(659, 600);
Beep(329, 100);
Beep(493, 300);
Beep(698, 300);
Beep(659, 600);
Beep(392, 250);
Beep(440, 200);
Beep(587, 300);
Beep(349, 250);
Beep(587, 400);
}
return 0;
}
Example 2: how to make a calculator in c++
#include <iostream>
using namespace std;
void greetings() {
cout << "welcome to the calculator made in c++ :D\n";
}
void instructions() {
cout << "Here is the operators you can use + - / *\n";
}
int main()
{
greetings();
instructions();
int num1, num2;
char op;
int result;
char again = 'Y';
while (again == 'y' || again == 'Y') {
cout << "\nEnter your first digit: ";
cin >> num1;
cout << "\nEnter your operator digit: ";
cin >> op;
cout << "\nEnter your second digit: ";
cin >> num2;
if (op == '+') {
result = num1 + num2;
}
else if (op == '-') {
result = num1 - num2;
}
else if (op == '*') {
result = num1 * num2;
}
else if (op == '/') {
result = num1 / num2;
}
else {
cout << "Invalid operator";
}
cout << "= " << result;
cout << "\nDo you want to restart the calculator? (Y or N)";
cin >> again;
}
system("pause>0");
return 0;
}