1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
#include <iostream> using namespace std; // Function to perform addition double add(double a, double b) { return a + b; } // Function to perform subtraction double subtract(double a, double b) { return a - b; } // Function to perform multiplication double multiply(double a, double b) { return a * b; } // Function to perform division double divide(double a, double b) { if (b != 0) { return a / b; } else { cout << "Error: Division by zero is not allowed." << endl; return 0; // Return 0 to indicate error } } int main() { double num1, num2; char op; cout << "Enter first number: "; cin >> num1; cout << "Enter an operator (+, -, *, /): "; cin >> op; cout << "Enter second number: "; cin >> num2; switch (op) { case '+': cout << "Result: " << add(num1, num2) << endl; break; case '-': cout << "Result: " << subtract(num1, num2) << endl; break; case '*': cout << "Result: " << multiply(num1, num2) << endl; break; case '/': cout << "Result: " << divide(num1, num2) << endl; break; default: cout << "Error: Invalid operator" << endl; break; } return 0; } |
Explanation
- Arithmetic Functions:
add(double a, double b)
: Returns the sum ofa
Advertisementb
.subtract(double a, double b)
: Returns the difference betweena
andb
.multiply(double a, double b)
Advertisementa
andb
.divide(double a, double b)
: Returns the quotient ofa
divided byb
. It checks ifb
is not zero to prevent division by zero and prints an error message ifb
is zero.
- Main Function:
- Prompts the user to enter two numbers and an operator.
- Uses a
switch
statement to determine which arithmetic operation to perform based on the entered operator. - Calls the appropriate function and prints the result.
Advertisement