Create a simple calculator with C++

Visual Studio Code Visual Studio Codeblocks

Sure! Here's an example of a simple calculator program written in C++ that can perform addition, subtraction, multiplication, and division:

#include <iostream>
using namespace std;

int main() {
    char operation;
    float num1, num2;

    cout << "Enter operator (+, -, *, /): ";
    cin >> operation;

    cout << "Enter two numbers: ";
    cin >> num1 >> num2;

    switch(operation) {
        case '+':
            cout << num1 << " + " << num2 << " = " << num1 + num2;
            break;

        case '-':
            cout << num1 << " - " << num2 << " = " << num1 - num2;
            break;

        case '*':
            cout << num1 << " * " << num2 << " = " << num1 * num2;
            break;

        case '/':
            if(num2 != 0)
                cout << num1 << " / " << num2 << " = " << num1 / num2;
            else
                cout << "Error: Division by zero!";
            break;

        default:
            cout << "Invalid operator!";
            break;
    }

    return 0;
}

Here's how it works:

It prompts the user to enter an operator (+, -, *, /). It then prompts the user to enter two numbers. Based on the operator entered, it performs the corresponding operation. The result is then displayed. Keep in mind that this is a very basic calculator and doesn't include error handling for cases like invalid input. Depending on your specific requirements, you might want to add more features or improve error handling.

Comments
Loading...
Sorry! No comment found:(

There is no comment to show for this.

Leave your comment
Tested Versions
  • GCC 6.3.0