如何将一笔钱兑换成纸币和硬币

时间:2014-08-18 21:33:02

标签: java arrays coin-change

如何将一定数量的钱兑换成纸币和硬币?让我们说输入是1234,26 我们有1000,500,200,100,50和20,20,1和0.5的硬币的钞票?因此,如果输入大于.25且小于0.75,如果它在.75和1.00之间,它应该四舍五入为1x 1,如果它小于.25则应该四舍五入为零?¨ 对于这个确切的程序,所需的输出看起来像这样:

1x: 1000
1x:  200
1x:   20
1x:   10
4x:    1
1x:    0.5

如果它不是0.5硬币,我想我可以使用int和%来做到这一点,但是现在我几乎无能为力(想想我必须使用数组,但我不知道如何)并且不知道如何开始。我也是初学者,如果你能在回答和解释时牢记这一点!任何提示/解决方案?提前谢谢!

像这样?:

   System.out.println((input/1000) + " thousand " + ((input/500)%2) + " fivehundred " + (input/200%2.5) + " two hundred " + (input/100%2) + " hundred " + (input/50%2) + " fifty " + (input/20%2.5) + " twenty " + (input/10%2) + " ten " + input/1%10 + " one " );

仍然不确定如何处理0.5因为我必须使用int,只输入cuz如果我使用double我得到它完全错误,我还必须使用if语句为0.5硬币..

1 个答案:

答案 0 :(得分:1)

我相信这是解决这类问题的标准方法。

double input = 1234.26;

int thousands = input/1000;
input = input - 1000*thousands;  //So now it would 234,26
int fivehundreds = input/500;
input = input - 500*fivehundreds;
etc...

是的,但你不能从double转换为int(即千位是int,但输入是double,所以input / 1000是double)。所以你有几个选择:

  1. 成千上万,五百等...加倍。但是,这有点难看,他们不会有任何小数值
  2. 施放对你来说意味着什么?例如,(int)int thousands = input/1000;将起作用。您可以阅读" cast",但基本上我只是告诉Java将该数字视为int,而不是双重
  3. 将输入保持为int,并将其向下舍入。然后只检查它是否有小数值(input % 1 > 0),如果有,则需要半美元。
相关问题