Creating A Calculator
Lesson 11Author : Afrixi
Last Updated : November, 2022
Table of Content
Creating A Calculator in C++
how to create a basic calculator program in C++. This calculator will prompt the user to enter two numbers and an operator (+, -, *, /), and then perform the corresponding calculation and output the result.
#include <iostream>
int main() {
double num1, num2, result;
char op;
std::cout << "Enter first number: ";
std::cin >> num1;
std::cout << "Enter second number: ";
std::cin >> num2;
std::cout << "Enter operator (+, -, *, /): ";
std::cin >> op;
switch (op) {
case '+':
result = num1 + num2;
break;
case '-':
result = num1 - num2;
break;
case '*':
result = num1 * num2;
break;
case '/':
result = num1 / num2;
break;
default:
std::cout << "Invalid operator" << std::endl;
return 1;
}
std::cout << "Result: " << result << std::endl;
return 0;
}
In this code, the user is prompted to enter two numbers and an operator. The numbers are stored in the variables num1
and num2
, and the operator is stored in the variable op
.
A switch
statement is used to perform the corresponding calculation based on the operator entered by the user. The result is stored in the variable result
.
Finally, the result is output to the console using std::cout
.
Note that this calculator program assumes that the user will enter valid input, and does not perform any error checking. It’s important to handle invalid input in a real-world application.