自学Java,我遇到了一个示例问题,要求我创建一个收银机程序,用美元,镍,季度,角钱和便士计算回客户的总变化。
我确定了用户输入,但获得正确的子单元是棘手的部分。例如:如果成本为4美元而招标金额为5美元,则很容易编写返回1美元的代码行。但我遇到的麻烦是在正确的领域需要多少硬币和硬币。 ex2:总成本$ 4.62,招标:$ 5,变更:$ 0.38
System.out.print("Enter the sale amount: $ ");
double sale = user.nextDouble();
System.out.print("Enter the amount tendered by customer: $ ");
double tendered = user.nextDouble();
double totalChange = (tendered - sale);
System.out.printf("TOTAL CHANGE: $ %.2f\n", totalChange);
dollars = totalChange/1;
quarters = totalChange/25;
dimes = totalChange/10;
nickels = totalChange/5;
pennies = totalChange/1;
System.out.printf("DOLLARS: %.2f\n", dollars);
System.out.printf("QUARTERS: %.2f\n", quarters);
System.out.printf("DIMES: %.2f\n", dimes);
System.out.printf("NICKELS: %.2f\n", nickels);
System.out.printf("PENNIES: %.2f\n", pennies);
我不需要答案(因为我想学习和自学),但是需要一些关于如何去做的建议。
编辑:我对这个算法做错了什么:
dollars = totalChange/1;
dollars = (int)dollars;
dl = totalChange % 1;
quarters = dl/0.25;
q = quarters % 0.25;
quarters = (int)quarters;
dimes = q / .10;
d = dimes % .10;
nickels = d / .5;
n = nickels % .5;
pennies = n / .1;
n = pennies/ .1;
答案 0 :(得分:1)
你走在正确的轨道上。在确定变化中的最大数量的全部美元之后,减去它。然后确定剩下的最大数量的季度。每个重复一次。它与你自己作为一个人一样。