如何让我的代码打印出更改?我使用模数但它只打印剩余的

时间:2016-09-23 00:31:14

标签: java int double

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作为&#34;美元的第一个语句中的余数:&#34; < / p>

1 个答案:

答案 0 :(得分:0)

你总是只看到一美元金额而没有硬币的原因是你提示用户输入美元金额。然后,您的代码将此美元金额乘以100以确定分数。因为输入总是dolars的倍数,所以在除以100之后永远不会有任何余数,因此永远不会有任何硬币。

如果你想看到一些硬币,那么允许用户输入带有小数分数的美元金额,作为double类型输入,然后你会看到这里的分数(没有双关语):

System.out.print("Enter the amount due: ");//Variable = amount
Scanner keyboard = new Scanner(System.in);
double amount = keyboard.nextDouble();       // e.g. 311.00

System.out.print("Enter the amount recieved from Customer: ");
Scanner keyboard2 = new Scanner(System.in);
double customer = keyboard2.nextDouble();   // e.g. 320.49

double change = customer - amount;          // 9.4900000

int remainingAmount = (int)(change * 100);  // 949

int numDollars = remainingAmount / 100;     // 9 (49 gets truncated)
remainingAmount = remainingAmount % 100;    // 49 remainder

int numQuarters = remainingAmount / 25;     // 1 (24 gets truncated)
remainingAmount = remainingAmount % 25;     // 24 remainder

int numDimes = remainingAmount / 10;        // 2 (4 gets truncated)
remainingAmount = remainingAmount % 10;     // 4 remainder

int numNickels = remainingAmount / 5;       // 0
remainingAmount = remainingAmount % 5;      // 4 remainder

int numPennies = remainingAmount;           // 4 pennies left

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);