简易控制台计算器程序异常:所有运算均返回0值求助
C++简易计算器返回0的问题修复
你的计算器所有运算返回0的核心问题是运算函数没有将计算结果赋值给返回变量,另外除法函数的运算顺序也有误,具体修复点如下:
问题分析
- 所有运算函数(
getsum、getdifference等)中,你仅写出了算术表达式(比如num1 + num2),但没有把结果赋值给要返回的变量(比如total)。这些未初始化的局部变量会包含随机值,在你的环境中表现为返回0。 getquotient函数里的除法顺序错误,应该是第一个数除以第二个数,而非反过来。
修正后的代码
#include <iostream> #include <cmath> using namespace std; float getsum(float num1, float num2){ return num1 + num2; // 直接返回运算结果,无需额外变量 } float getdifference(float num1, float num2){ return num1 - num2; } float getproduct(float num1, float num2){ return num1 * num2; } float getquotient(float num1, float num2){ // 添加除数为0的判断,避免运行时错误 if(num2 == 0){ cout << "Error: Division by zero!" << endl; return 0; } return num1 / num2; // 修正运算顺序 } int main() { float a, b; char x; cout << "Enter first number: "; cin >> a; cout << "Enter operation: "; cin >> x; cout << "Enter second number: "; cin >> b; if (x == '+'){ cout << getsum(a, b); } else if (x == '-'){ cout << getdifference(a, b); } else if (x == '*'){ cout << getproduct(a, b); } else if (x == '/'){ cout << getquotient(a, b); } else { cout << "Invalid operation!"; } return 0; }
额外优化建议
- 保留除法函数中的除数为0判断,避免程序因非法运算崩溃。
- 原代码中未使用的
ans变量已删除,简化代码结构。
内容的提问来源于stack exchange,提问作者naythe
相关产品推荐
相关产品推荐

