gpt4 book ai didi

Java 替换变量

转载 作者:行者123 更新时间:2023-12-02 00:17:37 24 4
gpt4 key购买 nike

如果直接输入变量(即(5.00, 20.00),它会完美地计算变化,但如果我用购买和金额替换这些值,它不会计算变化?

public static void makeChange()
{

double purchase;
double tendered;

Scanner scan = new Scanner (System.in);

System.out.println ("How much was the Purchase?");
purchase = scan.nextDouble();
System.out.println ("Amount Tendered");
tendered = scan.nextDouble();


System.out.println("Processing Transaction");
int ch[] = cd.makeChange(purchase, tendered); // does not calculate change correctly





...continued

最佳答案

您正在使用 double 进行算术和比较,一旦任何中间值是无法由 double 精确表示的数字,就会产生不可预测的结果。例如,考虑这个看似无辜的循环:

double value = 1.0;
double dime = 0.1;
while (value > 0) {
value -= dime;
System.out.println(value);
}

打印:

0.9
0.8
0.7000000000000001
0.6000000000000001
0.5000000000000001
0.40000000000000013
0.30000000000000016
0.20000000000000015
0.10000000000000014
1.3877787807814457E-16
-0.09999999999999987

有关为什么会出现这种情况的进一步阅读可以在这里找到:What Every Computer Scientist Should Know About Floating-Point Arithmetic .

正如您在上一个问题中所建议的,将您的 double 变量更改为 BigDecimal ,我认为您的问题将会消失。

关于Java 替换变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11626531/

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