我认为我在如何开发负责获取余数并检查是否可以从显示的更改类别中提取更改的代码部分存在逻辑问题。 它旨在衡量你欠某人多少变化的价值,并做出最有效的改变。
我目前的输出:
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;
}
}
答案 0 :(得分:1)
在处理货币时很常见,你需要只处理整数。
将所有变量更改为int
将为您提供正确的值,因为整数除法将确保238 / 200 = 1
。而不是双重划分,这将导致238.0 / 200.0 = 1.19
。
¹处理代码(以及现实生活)中的钱是一个难题。您需要以用户可读的形式显示输出,因此您不希望由于双重不精确的问题而将价格显示为5.0001 €
,但您不希望计算进行“急切”舍入,因此最终结果是关闭。最简单的方法之一就是采用最小的“原子”,即美分并仅处理它们。