【发布时间】:2017-01-31 17:26:45
【问题描述】:
public class Change {
public static void main(String[] args) {
System.out.print("Enter the amount due: ");//Variable = amount
Scanner keyboard = new Scanner(System.in);
int amount = keyboard.nextInt();
System.out.print("Enter the amount recieved from Customer: ");
Scanner keyboard2 = new Scanner(System.in);
int customer = keyboard2.nextInt();//variable = customer
double change = customer - amount;
System.out.println("You need to give to customer");
double remainingAmount = (double) (change * 100);
double numDollars = remainingAmount / 100;
remainingAmount = remainingAmount % 100;
double numQuarters = remainingAmount / 25;
remainingAmount = remainingAmount % 25;
double numDimes = remainingAmount / 10;
remainingAmount = remainingAmount % 10;
double numNickels = remainingAmount / 5;
remainingAmount = remainingAmount % 5;
double numPennies = remainingAmount;
System.out.println("Dollars: " + numDollars);
System.out.println("Quarters: " + numQuarters);
System.out.println("Dimes: " + numDimes);
System.out.println("Nickels: " + numNickels);
System.out.println("Pennies: " + numPennies);
}
}
当我尝试运行代码时,我只收到了剩余部分
例如,当我输入所需金额为247 并输入客户编号315 时,我在“美元:”的第一条语句中得到68 作为余数
【问题讨论】:
-
我使用了模数,但它只打印出余数呃,这就是模数的作用......
-
是的,我知道,但我想我没说对,我正在尝试取模数,然后将其进一步分解为下一个季度。例如,在我的示例中,需要给定 247 的数量。那么收到的金额是 315。余数是 68 对吗?我如何让它跳过它并从分配给 100 的美元开始进入季度?季度是序列中的下一个;但它只打印出第一个变量的余数。对不起!
-
您的代码中的逻辑对我来说实际上看起来不错。您使用除法确定给定硬币的数量,然后使用模数结转余数以尝试使用较小的硬币。你的输出出乎意料呢?
-
输入应付金额:247 输入从客户那里收到的金额:315 您需要给客户美元:68.0 硬币:0.0 硬币:0.0 镍:0.0 便士:0.0 @TimBiegeleisen 我的输出是 68第一个“美元:”中的剩余部分
-
您使用了余数运算符。 Java 中没有取模运算符。