gpt4 book ai didi

Java Double 值 = 0.01 更改为 0.009999999999999787

转载 作者:搜寻专家 更新时间:2023-10-30 21:44:44 27 4
gpt4 key购买 nike

<分区>

Possible Duplicate:
Why not use Double or Float to represent currency?

我正在为我的高中类(class)编写一个基本的 Java 命令行程序。我们现在只处理变量。它用于计算购买后零钱中任何类型的纸币和硬币的数量。这是我的程序:

class Assign2c {
public static void main(String[] args) {
double cost = 10.990;
int paid = 20;
double change = paid - cost;
int five, toonie, loonies, quarter, dime, nickel, penny;

five = (int)(change / 5.0);
change -= five * 5.0;

toonie = (int)(change / 2.0);
change -= toonie * 2.0;

loonies = (int)change;
change -= loonies;

quarter = (int)(change / 0.25);
change -= quarter * 0.25;

dime = (int)(change / 0.1);
change -= dime * 0.1;

nickel = (int)(change / 0.05);
change -= nickel * 0.05;

penny = (int)(change * 100);
change -= penny * 0.01;

System.out.println("$5 :" + five);
System.out.println("$2 :" + toonie);
System.out.println("$1 :" + loonies);
System.out.println("$0.25:" + quarter);
System.out.println("$0.10:" + dime);
System.out.println("$0.05:" + nickel);
System.out.println("$0.01:" + penny);
}
}

它应该一切正常,但在最后一步,当剩下 0.01 美元时,便士数应该是 1,但实际上是 0。在进入代码并将更改值输出到控制台几分钟后,我已经发现在最后一步,当 change = 0.01 时,它变为 0.009999999999999787。为什么会这样?

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