如何优化存钱罐中的硬币数量?

时间:2015-09-25 04:07:57

标签: java math

因此,在存钱罐类中,我有四个变量:penniesnickelsdimesquarters。如果我的用户输入三个nickels,我想将其转换为1个dime和1个nickel。我知道这是一个简单的问题,但我现在只是愚蠢。这是我现有的:

public void optimize() { //This whole method is 100% terrible.
    nickels = nickels + pennies/5;
    pennies -= (nickels*5);

    quarters = quarters + nickels/5;
    nickels -= (quarters*5);

    dimes = dimes + nickels/2;
    nickels -= (dimes*2);
}

1 个答案:

答案 0 :(得分:3)

public void optimize() {
  int total = (25 * quarters) + (10 * dimes) + (5 * nickels) + pennies

  quarters = (total/25); //note the integer division
  total = total % 25; //no more quarters, cut off 25 until we're less than 25

  dimes = (total/10);
  total = total % 10;

  nickels = (total/5);
  total = total % 5;

  pennies = total;  
}

似乎某些事情应该有效。