C++:是否需从main()传变量至其他模块获取返回值及代码优化咨询
问题解答与代码优化建议
核心问题:那两个变量是否必需?
完全不需要。你定义的double accountBalance=0;和double overDrawn=0;属于冗余变量——它们仅作为参数传入输入函数,但这两个函数的参数是传值调用,函数内部修改的只是参数的副本,且你在函数里直接通过cin覆盖了参数值,初始的0完全没起到作用。直接删掉这两个变量,同时修改输入函数去掉多余的参数即可。
其他代码优化建议
1. 修正类型错误(最关键的问题)
- 输入函数的返回类型:账户余额是带小数的数值,
acctBalInput当前返回int会截断小数,导致精度丢失,应改为double;透支次数是整数,overdrawInput应返回int,匹配实际逻辑。 - 手续费计算的类型错误:
feePercent被定义为int,赋值0.01会直接被截断为0,导致余额的1%计算完全错误,必须改为double;feeCalculation的参数bal当前是int,接收double类型的余额会隐式转换丢失小数,应改为double,返回的手续费也应为double。
2. 简化输入函数,去掉冗余参数
输入函数不需要接收外部参数,直接在函数内部定义变量接收用户输入即可,比如:
double acctBalInput() { double bal; std::cout << "Enter account balance: "; std::cin >> bal; return bal; }
3. 简化main函数的变量声明
可以直接将函数返回值赋值给变量,无需先声明再赋值,让代码更简洁:
int main() { double balance = acctBalInput(); int overdrawCount = overdrawInput(); double totalFee = feeCalculation(balance, overdrawCount); display(balance, overdrawCount, totalFee); return 0; }
4. 规范代码风格
- 避免
using namespace std;,直接使用std::cout、std::cin,减少命名冲突风险; - 变量名更直观,比如把
drawn改成overdrawCount,一眼就能看懂含义; - 注释可以补充计算规则,比如在
feeCalculation里说明手续费是「余额的1% + 透支次数×5」。
修改后的完整代码
#include <iostream> // 输入账户余额 double acctBalInput(); // 输入透支次数 int overdrawInput(); // 计算手续费:余额的1% + 透支次数×5 double feeCalculation(double bal, int drawCount); // 显示结果 void display(double bal, int drawCount, double fee); int main() { double balance = acctBalInput(); int overdrawCount = overdrawInput(); double totalFee = feeCalculation(balance, overdrawCount); display(balance, overdrawCount, totalFee); return 0; } double acctBalInput() { double bal; std::cout << "Enter account balance: "; std::cin >> bal; return bal; } int overdrawInput() { int count; std::cout << "Enter the number of times over drawn: "; std::cin >> count; return count; } double feeCalculation(double bal, int drawCount) { const double FEE_PERCENT = 0.01; const int DRAW_FEE = 5; return bal * FEE_PERCENT + drawCount * DRAW_FEE; } void display(double bal, int drawCount, double fee) { std::cout << "Balance: " << bal << std::endl << "Overdrawn times: " << drawCount << std::endl << "Total fee: " << fee << std::endl; }
内容的提问来源于stack exchange,提问作者Mr. Puli
相关产品推荐
相关产品推荐

