simple c++ calculator code example

Example 1: 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;
}

Example 2: how to make a calculator in c++

// This is for beginners

#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;
}

Tags:

Cpp Example