我记得这是一个我可以遇到的问题,但我忘记了原因。这是我的代码。
import java.util.Scanner;
public class GroceryTab
{
public static void main(String[] args)
{
double total = 0;
int items = 0;
System.out.print("How many different products are you buying?");
Scanner in = new Scanner(System.in);
items = in.nextInt();
for(int i=1; i<=items; i++) {
double price;
int numberBought;
System.out.print("What is the price of your " + i +"th item?");
Scanner priceIn = new Scanner(System.in);
price = priceIn.nextDouble();
System.out.print("How many of this item are you buying?");
Scanner numIn = new Scanner(System.in);
numberBought = numIn.nextInt();
total += (price * numberBought);
}
System.out.print("Your list costs " + total + " dollars.");
}
}
这是奇怪的部分。我正在测试它,我把它放在下面:
您购买了多少种不同的产品?2
第1件商品的价格是多少?30.32
你买了多少这个项目?3
第2件商品的价格是多少?.01
你买了多少这个项目?3
得到了
您的清单费用为90.99000000000001美元。
糟糕!我是怎么做到的?
答案 0 :(得分:6)
我只是评论,但没有代表......
这是因为您使用了双(或一般的浮点)。如果你需要精确的精度,BigDecimal会更好,但速度会更慢。
答案 1 :(得分:0)
此处的浮点(price
和total
为double
)并不确切;如果您想让价格更加精确,一种可能的解决方法是跟踪价格int
s(可能是美分)。
答案 2 :(得分:0)
它必须处理双精度。我建议使用
DecimalFormat df = new DecimalFormat("#.00");
System.out.print("Your list costs " + df.format(total) + " dollars.");
或类似的东西,因为你使用美元并且不想要.ooooo1美分。无论如何,这不是你的问题。它只是精度的双倍并不是最好的。
答案 3 :(得分:0)
使用BigDecimal并正确执行:
BigDecimal total = BigDecimal.ZERO;
System.out.print("How many different products are you buying?");
Scanner in = new Scanner(System.in);
int items = in.nextInt();
for (int i=1; i<=items; i++) {
System.out.print("What is the price of your " + i +"th item?");
Scanner priceIn = new Scanner(System.in);
BigDecimal price = priceIn.nextBigDecimal();
System.out.print("How many of this item are you buying?");
Scanner numIn = new Scanner(System.in);
int numberBought = numIn.nextInt();
BigDecimal lineTot = price.multiply( BigDecimal.valueOf(numberBought));
total = total.add( lineTot);
}
System.out.print("Your list costs " + total + " dollars.");
样式建议:如果只有最初分配该值的代码路径,则在分配值之前不要声明变量。
如果你出现在商业软件开发的工作面试中,那么我不知道如何正确定点,你不会被录用。