gpt4 book ai didi

java - 输出不正确的总输出

转载 作者:行者123 更新时间:2023-11-29 04:32:37 25 4
gpt4 key购买 nike

如果您输入,我当前的程序会发出比萨饼订单

moho

这是一个中等比萨饼,橄榄,火腿,橄榄的价格输出应该是:

Medium pizza with,olives,ham,olives,£7.00

但是,我得到:

Your order is: Medium pizza with,olives,ham,olives,£6.999999999999999

我怎样才能让它打印出正确的输出?我已经查看了代码,但似乎无法弄清楚原因。

    public class pizza {
public static void main(String[] args){
pizzaServiceA();
}
public static void pizzaServiceA(){
Scanner input = new Scanner(System.in);
double total = 0;
System.out.println("Enter order:");
String order = input.next();
String pizza = "Your order is: ";

if (order.equals("quit")){
System.out.println("Program exiting.");
System.exit(0);
}

boolean size = false;
for (int x = 0; x < order.length(); x++){
if (order.charAt(0) == 'm' || order.charAt(0) == 'l'){
if (order.charAt(x) == 'm'){
total +=4.00;
pizza += "Medium pizza with,";
size = true;
}
else if (order.charAt(x) == 'l'){
total +=5.00;
pizza +="Large pizza with,";
}
else if (order.charAt(x) == 'h'){
pizza +="ham,";
if (size) total += 1.40;
else total +=2.10;
}
else if (order.charAt(x)== 'o'){
pizza +="olives,";
if(size) total +=0.80;
else total +=1.20;
}
else if (order.charAt(x)=='p'){
pizza+="pineapple,";
if(size) total +=1;
else total+=1.50;
}
else if (order.charAt(x)=='s'){
pizza+="spinach,";
if(size) total +=0.80;
else total+=1.20;
}
else if (order.charAt(x)=='m'){
pizza +="mozarella,";
if(size) total =+ 1;
else total+=1.50;
}
}
else {
System.out.println("Your first character must be m(medium) or l(large)");
}
}
System.out.println(pizza +"£" + total + "0");
}
}

注意:我知道我可能没有以有效的方式编写此代码,因为我只是 Java 的初学者并且我正在努力学习。

最佳答案

这集中体现了使用二进制浮点类型来表示精确货币值的缺陷。

为了轻松生活(尤其是考虑到您是初学者),请使用整数类型(例如 long)并以便士的形式工作。

有关详细信息,请参阅 Is floating point math broken?

关于java - 输出不正确的总输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43208492/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com