我最近遇到了 Java 代码的这种意外输出。请让我知道您对它有什么问题的看法。
public static int calculateTotalPrice(int[] prices, int discount){
int total = 0;
for(int i =0;i<prices.length;i++){
total += prices[i];
}
float amount = total - (total * discount / 100);
return Math.round(amount);
}
对于给定输入,预期输出为 620。
<块引用>店主要求您实施该方法 calculateTotalPrice(prices,discount),获取价格列表 客户购买的产品和百分比折扣为 参数并以整数形式返回总购买价格(四舍五入 如果总数是浮点数,则向下)。
“编码游戏”编译器给出的输入是:价格[] = {100, 200, 400},折扣= 20%
运行代码后我的输出:560
编码游戏说:预期输出:620
我尝试了很多东西,但找不到方法。为什么我的输出不正确?
答案 0 :(得分:1)
您的基本计算是正确的,对于您提供的整数值,正确的输出确实是 560。
但是有两个问题:
如果折扣计算为浮点数,您的结果将不正确。您需要强制计算为浮点计算,例如像这样(注意 100f
):
float amount = total - (total * discount / 100f);
如果结果是浮点数,作业要求您向下舍入。 Math.round()
不向下舍入,而是舍入到最接近的整数。您需要改用 Math.floor()
或直接转换为 int
:
return (int) Math.floor(amount);
// or
return (int) amount;