C++ if语句使用异常:仅加法运算正常,其余运算失效
C++ if语句逻辑错误导致运算异常的修复
问题现象
编写运算程序时,输入加法运算可正常输出结果,但输入减法、乘法或除法运算时,程序无法按预期工作。
作业要求
编写一个程序,接收一个操作符及两个操作数并输出结果。例如:
- 100 3.14
- 4 5
将操作符读取到名为operation的string变量中,使用if语句判断用户需求(如if (operation=="+")),将操作数读取为double类型。需支持+、–、*、/、plus、minus、mul、div这些操作。
原代码
#include <iostream> using namespace std; int main(){ cout<<"Enter an operation below following this template operation operand operand:\n\n"; char user_operation; double user_operand_one, user_operand_two; cin>>user_operation; cin>>user_operand_one; cin>>user_operand_two; double plus_result, div_result, minus_result, mul_result; //formulas plus_result = user_operand_one + user_operand_two; minus_result = user_operand_one - user_operand_two; div_result = user_operand_one / user_operand_two; mul_result = user_operand_one * user_operand_two; if (user_operation == '+' || "plus") { cout<<'\n'<<plus_result; } else if (user_operation == '-' || "minus") { cout<<'\n'<<minus_result; } else if (user_operation == '*' || "mul"){ cout<<'\n'<<mul_result; } else if (user_operation == '/' || "div"){ cout<<'\n'<<div_result; } }
使用编译器:gcc 12.2.0
问题分析
- 操作符类型错误:作业明确要求用
string存储操作符,但代码中用了char类型。输入"plus"这类字符串操作符时,cin只会读取第一个字符,剩余字符会干扰后续操作数的读取;同时char无法存储完整的字符串操作符,直接丢失了对"plus""minus"等指令的判断能力。 - if条件逻辑错误:
if (user_operation == '+' || "plus")写法不符合C++逻辑,||右侧的"plus"是字符串字面量,非空指针在布尔判断中会被视为true,导致第一个if条件永远成立。无论输入什么操作符,程序都会执行加法结果的输出,这是减乘除运算异常的核心原因。 - 冗余计算:提前计算所有运算结果,在只需要执行一种运算的场景下属于不必要的性能浪费。
修正后的代码
#include <iostream> #include <string> // 引入string头文件以支持字符串类型 using namespace std; int main(){ cout << "Enter an operation below following this template operation operand operand:\n\n"; string operation; // 改用string存储操作符 double operand1, operand2; cin >> operation >> operand1 >> operand2; // 合并输入读取,简化代码 if (operation == "+" || operation == "plus") { cout << "\n" << operand1 + operand2; } else if (operation == "-" || operation == "minus") { cout << "\n" << operand1 - operand2; } else if (operation == "*" || operation == "mul") { cout << "\n" << operand1 * operand2; } else if (operation == "/" || operation == "div") { // 新增除数为0的判断,避免运行时错误 if (operand2 == 0) { cout << "\nError: Division by zero is not allowed."; } else { cout << "\n" << operand1 / operand2; } } else { // 新增非法操作符提示,提升程序健壮性 cout << "\nError: Unsupported operation."; } return 0; }
修正说明
- 将操作符变量类型从
char改为string,支持读取所有要求的操作符类型。 - 修正if条件判断逻辑,每个分支都完整判断操作符是否匹配目标值。
- 合并输入读取语句,简化代码结构;仅在匹配到对应操作符时才计算结果,避免冗余计算。
- 新增除数为0的错误处理和非法操作符提示,提升程序的健壮性。
内容的提问来源于stack exchange,提问作者Beginner
相关产品推荐
相关产品推荐

