60.1k views
0 votes
Write a C++ program that reads three input from the user:

One character representing an operation
Two real values (floating point) representing 2 operands
The program should perform the operation on the two operands and display the result.
The valid operations are:
‘+’ for addition
‘-‘ for subtraction
‘*’ for multiplication
‘/’ for division (should avoid division by 0)
The program should display ""Invalid Operation"" in case the input is any other character. Use switch statement to decide which operation to perform.
Example:
For the input: + 3.5 4.3
The result should be: 7.8

1 Answer

6 votes

Final answer:

A C++ program is provided that reads a character operation (+, -, *, /) and two floating point numbers from the user, performs the operation, and displays the result. It uses a switch statement to handle the operations and checks for division by zero.

Step-by-step explanation:

The student asked for a C++ program that reads a character and two floating point numbers from the user, performs an operation based on the character provided, and prints the result. The program uses a switch statement to handle the operations of addition, subtraction, multiplication, and division, and includes a default case to handle invalid operations. Below is the requested C++ program:

#include
using namespace std;

int main() {
char operation;
double operand1, operand2;

cout << "Enter an operation (+, -, *, /) followed by two numbers: ";
cin >> operation >> operand1 >> operand2;

switch(operation) {
case '+':
cout << (operand1 + operand2) << endl;
break;
case '-':
cout << (operand1 - operand2) << endl;
break;
case '*':
cout << (operand1 * operand2) << endl;
break;
case '/':
if(operand2 != 0) {
cout << (operand1 / operand2) << endl;
} else {
cout << "Division by zero is not allowed." << endl;
}
break;
default:
cout << "Invalid Operation" << endl;
}

return 0;
}

The program should be compiled and run by the student. When executed, it will prompt the user for an operation and two operands, then perform the specified operation and display the result, being careful to avoid division by zero.

User Jan Olaf Krems
by
7.1k points