convertCurrency函数测试未全过:-500金额用例失败排查
问题排查:convertCurrency函数参数校验逻辑错误
问题场景
需求实现convertCurrency函数:
- 接收格里夫纳金额(
amount)、汇率(exchangeRate)、目标货币名称(currencyName)三个参数 - 返回格式为
Give them {{x}} {{currencyName}}('s)的字符串 - 参数校验规则:若
amount和/或exchangeRate为负数或零,返回Enter valid data;计算结果非整数需保留两位小数
当前代码在测试用例amount=-500,exchangeRate=0.14,currencyName='peso'时,未正确返回错误提示。
错误原因分析
原代码的条件判断逻辑存在两处关键错误:
- 第一个条件逻辑错误:
if (amount && exchangeRate > 0)中,负数(如-500)属于JavaScript的truthy值(非零数字均为truthy),所以当amount=-500时,amount会被判定为true,结合exchangeRate>0的true结果,整个条件成立,错误进入了正常计算分支。 - 第二个条件逻辑错误:
else if (amount || exchangeRate <= 0)的逻辑完全不符合需求,且运算符优先级导致实际判断为amount || (exchangeRate <=0),即使参数非法,也无法触发该分支。
修正方案
调整参数校验逻辑,先直接判断非法情况,再处理正常计算:
function convertCurrency(amount, exchangeRate, currencyName) { // 优先校验参数合法性:只要任一参数<=0就返回错误 if (amount <= 0 || exchangeRate <= 0) { return 'Enter valid data'; } const result = amount * exchangeRate; // 格式化结果:整数直接返回,非整数保留两位小数 const formattedResult = Number.isInteger(result) ? result : result.toFixed(2); // 优化复数显示:结果为1时不加's' const currencyLabel = result === 1 ? currencyName : `${currencyName}'s`; return `Give them ${formattedResult} ${currencyLabel}`; }
关键修正点
- 把参数校验放在最前端,用
amount <=0 || exchangeRate <=0精准匹配所有非法情况,逻辑清晰且符合需求 - 修复了原代码中负数被误判为合法参数的问题
- 优化了货币名称的复数显示逻辑,避免出现
1 peso's这类语义错误
内容的提问来源于stack exchange,提问作者ali98ab
相关产品推荐
相关产品推荐

