gpt4 book ai didi

java - 使用%找零时给出错误的数字

转载 作者:行者123 更新时间:2023-12-01 22:06:19 24 4
gpt4 key购买 nike

我正在创建一个回馈零钱的系统。当我运行该程序时,我得到:(假设我捐了 100 美元)

You have given 100.0 dollars.
Your change is 14.670000000000002 dollars.
You will recieve:
0.6700000000000017 dollars
0.1700000000000017 quarters
0.0700000000000017 dimes
0.020000000000001697 nickels
1.6965595595053173E-15 pennies

代码

import java.util.Scanner;
public class RunGivingChange {

public static void main(String[] args) {
// TODO Auto-generated method stub

double given;
double cost = 85.33;
double change;
int dollars;
int quarters;
int dimes;
int nickels;
int pennies;

Scanner input = new Scanner(System.in);

System.out.println("Your total is " + cost + " dollars.");
System.out.println("How much money are you giving?");
given = input.nextDouble();
if (given >= cost)
{
System.out.println("You have given " + given + " dollars.");
change = given - cost;
System.out.println("Your change is " + change + " dollars.");
System.out.println("You will recieve:");

//dollars
change = change % 1;
System.out.println(change + " dollars");

//quarters
change = change % 0.25;
System.out.println(change + " quarters");

//dimes
change = change % 0.10;
System.out.println(change + " dimes");

//nickels
change = change % 0.05;
System.out.println(change + " nickels");

//pennies
change = change % 0.01;
System.out.println(change + " pennies");
}
else if (given < cost)
{
System.out.println("Not enough money.");
}
else
{
System.out.println("Error.");
}

}

}

最佳答案

您使用 double 浮点值来表示金钱。

不要这样做。

float 的精度约为 15 位有效数字,但其范围(和计算性能)惊人,使其可用于科学用途。

使用定点类型或 BigDecimal 表示货币值。

关于java - 使用%找零时给出错误的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32716393/

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