Sunday, 29 April 2012

Calculator in C++ using Switch-Case


#include <iostream>

int   output;      
char  operation;  
int   value;       

int main(  )
{
    output = 0;                
    while (true) {
        std::cout << "output: " << output << '\n';
        std::cout << "Enter operator and number: ";

        std::cin >> operation >> value;

        if ((operation == 'q') || (operation == 'Q'))
            break;

        switch (operation) {
            case '+':
                output += value;
                break;
            case '-':
                output -= value;
                break;
            case '*':
                output *= value;
                break;
            case '/':
                if (value == 0) {
                    std::cout << "Error:Divide by zero\n";
                    std::cout << "   operation ignored\n";
                } else
                    output /= value;
                break;
            default:
                std::cout << "Unknown operator " << operation << '\n';
                break;
        }
    }
    return (0);
}

No comments:

Post a Comment