Example input
Here is some c++ code for a calculator. I am a novice and have no experience in coding.
Please add more operator options and maintain the functionality of this code.
CODE:
# include <iostream>
using namespace std;
int main() {
char op;
float num1, num2;
cout << "Enter operator: +, -, *, /: ";
cin >> op;
cout << "Enter two operands: ";
cin >> num1 >> num2;
switch(op) {
case '+':
cout << num1 << " + " << num2 << " = " << num1 + num2;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1 - num2;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1 * num2;
break;
case '/':
cout << num1 << " / " << num2 << " = " << num1 / num2;
break;
default:
// If the operator is other than +, -, * or /, error message is shown
cout << "Error! operator is not correct";
break;
}
return 0;
}
Example output
Certainly! I can modify this code to include more operator options while maintaining its functionality. Here's the modified code:
#include <iostream>
using namespace std;
int main() {
char op;
float num1, num2;
cout << "Enter operator: +, -, *, /, %, ^: ";
cin >> op;
cout << "Enter two operands: ";
cin >> num1 >> num2;
switch(op) {
case '+':
cout << num1 << " + " << num2 << " = " << num1 + num2;
break;
case '-':
cout << num1 << " - " << num2 << " = " << num1 - num2;
break;
case '*':
cout << num1 << " * " << num2 << " = " << num1 * num2;
break;
case '/':
if(num2 != 0) {
cout << num1 << " / " << num2 << " = " << num1 / num2;
} else {
cout << "Error! Cannot divide by zero.";
}
break;
case '%':
if(num2 != 0) {
cout << num1 << " % " << num2 << " = " << (int)num1 % (int)num2;
} else {
cout << "Error! Cannot divide by zero.";
}
break;
case '^':
cout << num1 << " ^ " << num2 << " = " << pow(num1, num2);
break;
default:
// If the operator is other than +, -, *, /, %, or ^, error message is shown
cout << "Error! Operator is not correct.";
break;
}
return 0;
}
I have added two more operator options: the modulus operator % and the power operator ^. The modulus operator computes the remainder when num1 is divided by num2, while the power operator raises num1 to the power of num2.
Note that I have also added some input validation to handle cases where num2 is zero, to avoid dividing by zero. The modulus operator also only works with integer operands, so I have cast num1 and num2 to integers using the (int) operator.
I hope this helps! Let me know if you have any questions or need further assistance.