【发布时间】:2019-12-20 03:09:28
【问题描述】:
我的代码有问题,每次我输入除运算符 (+,/,*,-) 以外的其他内容时,它仍然会要求输入数字。我希望它停止并显示文本“错误!运算符不正确”,当有人将其他东西放在运算符之外时
#include <iostream>
using namespace std;
int main()
{
char op;
float num1, num2;
cout << "Enter operator either + or - or * or /: ";
cin >> op;
cout << "Enter the first operand: ";
cin >> num1;
cout << "Enter the second operand: ";
cin >> num2;
switch (op)
{
case '+':
cout << num1 + num2;
break;
case '-':
cout << num1 - num2;
break;
case '*':
cout << num1 * num2;
break;
case '/':
cout << num1 / num2;
break;
default:
cout << "Error! operator is not correct";
break;
}
return 0;
}
【问题讨论】:
-
它的行为与您编写的完全一样 - 提示并读取一个字符,然后提示并读取两个整数,然后仅检查
op的值。op读完后需要立即检查,在提示和读取后续整数值之前。
标签: c++ computer-science