gpt4 book ai didi

java 欧元硬币找零面额

转载 作者:行者123 更新时间:2023-11-30 07:08:29 25 4
gpt4 key购买 nike

我相信我在如何开发负责获取剩余部分并检查是否可以从显示的更改类别中提取更改的代码部分方面遇到了逻辑问题。它旨在计算您欠某人的找零金额,并做出最有效的找零。

我当前的输出:

The change for 328.0 Euro cents is:
1.64 € 2
1.28 € 1
0.56 € 0.50
1.4 € 0.20
0.8 € 0.10
1.6 € 0.05
1.5 € 0.02
1.0 € 0.01

正确输出:

The change for 328 Euro cents is:
1 €2
1 €1
0 €0.50
1 €0.20
0 €0.10
1 €0.05
1 €0.02
1 €0.01

我很困惑,非常感谢您的帮助,谢谢。

import java.util.Scanner; // Enables user input

public class Change {
private static Scanner scnr;

public static void main(String [] args) {
scnr = new Scanner(System.in);
double changeR = 0; // User input
double oneCent = 0; // Number of one cent coins
double twoCent = 0; // Number of two cent coins
double fiveCent = 0; // Number of five cent coins
double tenCent = 0; // Number of ten cent coins
double twentyCent = 0; // Number of twenty cent coins
double fiftyCent = 0; // Number of fifty cent coins
double oneEUC = 0; // Number of one Euro cent coins
double twoEUC = 0; // Number of two Euro cent coins

System.out.println("Please enter the amount of change in Euro cents to be returned (a number between 0 & 499): ");
changeR = scnr.nextInt(); // Gathers user input

System.out.println("The change for " + changeR + " Euro cents is: "); // Outputs users inputted value

twoEUC = changeR / 200;
changeR = changeR % 200;

oneEUC = changeR / 100;
changeR = changeR % 100;

fiftyCent = changeR / 50;
changeR = changeR % 50;

twentyCent = changeR / 20;
changeR = changeR % 20;

tenCent = changeR / 10;
changeR = changeR % 10;

fiveCent = changeR / 5;
changeR = changeR % 5;

twoCent = changeR / 2;
changeR = changeR % 2;

oneCent = changeR / 1;
changeR = changeR % 1;

System.out.println( twoEUC + " \u20ac" + " 2");
System.out.println( oneEUC + " \u20ac" + " 1");
System.out.println( fiftyCent + " \u20ac" + " 0.50");
System.out.println( twentyCent + " \u20ac" +" 0.20");
System.out.println( tenCent + " \u20ac" +" 0.10");
System.out.println( fiveCent + " \u20ac" +" 0.05");
System.out.println( twoCent + " \u20ac" +" 0.02");
System.out.println( oneCent + " \u20ac" +" 0.01");

return;
}
}

最佳答案

与处理金钱时常见的情况一样,您只需要处理整数。

将所有变量更改为 int 将为您提供正确的值,因为整数除法将确保 238/200 = 1。而不是双除法,结果是 238.0/200.0 = 1.19

1 在代码(以及现实生活)中处理金钱是一个难题。您需要以用户可读的形式呈现输出,因此由于双重不精确的问题,您不希望将价格显示为 5.0001 €,但您也不希望计算“急切” "四舍五入,所以最终结果是关闭的。最简单的方法之一是采用最小的“原子”,即美分并仅对其进行交易。

Why not use double or float to represent currency

关于 java 欧元硬币找零面额,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39626410/

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