C++ deposit与withdrawl函数冗余第二参数的优化方案咨询
优化方案
方案1:直接删除冗余参数(适配现有逻辑的最小改动)
你当前代码中deposit、withdrawl函数的第二个参数完全没有用到外部传入的值,进入函数后立刻被用户输入的内容覆盖,属于无效冗余参数,直接删除即可解决必须传无用参数的问题。
修改后的函数代码如下:
// 仅保留当前余额一个入参,存取款金额改为函数内部局部变量 int deposit(int cBalance) { int dBalance; cout << "How much would you like to deposit?" << endl; cin >> dBalance; cout << "Processing Deposit......." << endl; cBalance += dBalance; return cBalance; } int withdrawl(int cBalance) { int wBalance; cout << "How much would you like to withdraw?" << endl; cin >> wBalance; cout << "Processing Withdrawl......." << endl; while (wBalance > cBalance) { cout << "NOT ENOUGH FUNDS. Try Again" << endl; cout << "How much would you like to withdraw?" << endl; cin >> wBalance; } cBalance -= wBalance; return cBalance; }
对应的main函数调用逻辑修改为:
if (moneyActivity == "deposit") { currentBalance = deposit(currentBalance); cout << "Transaction Successful! Your Final Balance is: $ " << currentBalance << endl; } else if (moneyActivity == "withdraw") { currentBalance = withdrawl(currentBalance); cout << "Transaction Successful! Your Final Balance is: $ " << currentBalance << endl; }
同时可以删除main函数中无用的int depositAmount, withdrawAmount;变量定义,彻底规避未初始化变量传参的潜在隐患。
方案2:拆分职责(复用性更强的优化写法)
如果希望函数的通用性更高,可将「用户输入交互」和「余额计算核心逻辑」拆分,存取款函数仅负责余额计算,输入校验逻辑放到外层处理,后续对接其他金额输入渠道(比如批量交易、接口传参)时不需要修改核心计算逻辑。
修改后的核心函数代码如下:
// 仅处理存款余额计算 int deposit(int cBalance, int dBalance) { cout << "Processing Deposit......." << endl; return cBalance + dBalance; } // 仅处理取款余额计算 int withdrawl(int cBalance, int wBalance) { cout << "Processing Withdrawl......." << endl; return cBalance - wBalance; }
对应的main函数调用逻辑修改为:
if (moneyActivity == "deposit") { int dBalance; cout << "How much would you like to deposit?" << endl; cin >> dBalance; currentBalance = deposit(currentBalance, dBalance); cout << "Transaction Successful! Your Final Balance is: $ " << currentBalance << endl; } else if (moneyActivity == "withdraw") { int wBalance; cout << "How much would you like to withdraw?" << endl; cin >> wBalance; while (wBalance > currentBalance) { cout << "NOT ENOUGH FUNDS. Try Again" << endl; cout << "How much would you like to withdraw?" << endl; cin >> wBalance; } currentBalance = withdrawl(currentBalance, wBalance); cout << "Transaction Successful! Your Final Balance is: $ " << currentBalance << endl; }
内容的提问来源于stack exchange,提问作者Aaradhya Poudyal
相关产品推荐
相关产品推荐

