计算用户对2个输入的变化

时间:2016-10-20 21:29:53

标签: java

我正在尝试输出两个输入所需的最少量音符。一个是成本,另一个是客户交付的金额。

所以,如果我输入400然后是500,它应该说2美元50美元的钞票。 或者,如果我输入60,然后是80,则应该说1美元20美元的钞票。

这是我的一小部分代码:

import java.util.Scanner;

public class bank {

public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

     System.out.println("Enter amount due: ");
     int amount = input.nextInt();

     System.out.println("Amount tendered: ");
     int tmp = input.nextInt();

     int change;

     if(amount >= 50)
         {
         change =(tmp - amount)/50;
         System.out.println (change + " $50 bills");

         }

     if(amount >= 20)
     {
         change =(tmp - amount)/20;
         System.out.println (change + " $20 bills");

     }

3 个答案:

答案 0 :(得分:0)

您可以使用mod运算符%

来实现它
public static void main(String[] args) {

    Scanner input = new Scanner(System.in);

    System.out.println("Enter amount due: ");
    int amount = input.nextInt();

    System.out.println("Amount tendered: ");
    int tmp = input.nextInt();

    int change;

    int diff = tmp - amount;
    if (diff % 50 == 0) {
        change = diff / 50;
        System.out.println(change + " $50 bills");

    } 
    else if (diff % 20 == 0) {
        change = diff / 20;
        System.out.println(change + " $20 bills");

    }
}

答案 1 :(得分:0)

计算账单价值的变化金额后,您需要降低所需的变更金额。这是在代码changeRequired = changeRequired - change;

中完成的
 System.out.println("Amount tendered: ");
 int tmp = input.nextInt();

 int changeRequired = tmp - amount;    

 int change;

 if(amount >= 50)
     {
     change =(changeRequired)/50;
     changeRequired = changeRequired - change;
     System.out.println (change + " $50 bills");

     }

 if(amount >= 20)
 {
     change =(changeRequired )/20;
     changeRequired = changeRequired - change;
     System.out.println (change + " $20 bills");

 }

答案 2 :(得分:0)

获得变量amount后,您可以使用以下代码查看更改中每个$ 50,$ 20,$ 10,$ 5,$ 1的注释数。笔记数量很少。

numOf50 = 0; // number of $50 dollar bills, the rest is similar.
numOf20 = 0; // ...
numOf10 = 0; // ...
numOf5 = 0;
numOf1 = 0;


    if (amount / 50 > 1){
        numOf50 += (amount / 50);
        amount %= 50; // update the amount with the remainder
    }
    else if (amount / 20 > 1){
        numOf20 += (amount /20);
        amount %= 20;
    }
    else if (amount / 10 > 1){
        numOf10 += (amount / 10);
        amount %= 10;
    }
    else if (amount / 5 > 1){
        numOf5 += (amount / 5);
        amount %= 5;
    }
    else if (amount <=5 && amount >0){
        numOf1 = amount;
    }
// output is trivial, omitted.

没有在机器上进行测试,但它应该可以工作或给你一个想法。