Modify program 2 to ask the user for an opcode (1 for +, 2 for -, 3 for/and 4 fo
ID: 3857064 • Letter: M
Question
Modify program 2 to ask the user for an opcode (1 for +, 2 for -, 3 for/and 4 for *). Make your program do the requested operation. Here's sample output enter 1 for plus, 2 for subtract, 3 for divide and 4 for multiply 1 thank you, now enter the two operands 4 5 4 + 5 = 9 Process returned 0 (0 times 0) execution time: 6.630 = Press any to continue. Also put in a check for divide by zero and print out a warning message. Here is the program run for divide with the divide by zero case. enter for plus, 2 for subtract, 3 for divide and 4 for multiply 3 thank you, now enter the operands 5 0 5/0 = error, can't divide by zeroExplanation / Answer
Since you didn't specify a language, I coded it in C++. The code for it can be found below. Feel free to ask if any doubt still persists, and I'll be happy to help.
Note: (float)num1 / (float)num2 is called Type-casting and is done to prevent integer division, according to which 5/2 = 2.
Code :
#include <iostream>
using namespace std;
int main()
{
int opcode;
cout << "enter 1 for plus, 2 for subtract, 3 for divide and 4 for multiply ";
cin >> opcode;
int num1, num2;
cout << "thank you, now enter the two operands ";
cin >> num1 >> num2;
if(opcode == 1)
{
cout << num1 << " + " << num2 << " = " << num1 + num2 << " ";
}
else if(opcode == 2)
{
cout << num1 << " - " << num2 << " = " << num1 - num2 << " ";
}
else if(opcode == 3)
{
if(num2==0)
{
cout << num1 << " / " << num2 << " = " << "error, can't divide by zero ";
}
else
{
cout << num1 << " / " << num2 << " = " << (float)num1 / (float)num2 << " ";
}
}
else
{
cout << num1 << " * " << num2 << " = " << num1 * num2 << " ";
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.