Java程序,告诉我们从1美分到99美分的任何变化金额 [英] Java program that tells what coins to give out for any amount of change from 1 cent to 99 cents

查看:141
本文介绍了Java程序,告诉我们从1美分到99美分的任何变化金额的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须编写一个Java程序,告诉我们从1美分到99美分的任何变化金额。例如,如果金额为86美分,则输出结果如下:

I have to write a Java program that tells what coins to give out for any amount of change from 1 cent to 99 cents. For example, if the amount is 86 cents, the output would be something like the following:


86美分可以给出3个季度, 1美分和1美分。

86 cents can be given as 3 quarters, 1 dime and 1 penny.

使用25,10,5和1的硬币面额。您的程序将使用以下方法(其中):

Use coin denominations of 25, 10, 5, and 1. Your program will use the following method(among others):

public static int computeCoin(int coinValue,);
// Precondition: 0 < coinValue < 100; 
// Postcondition: returned value has been set equal to the maximum 
//number of coins of the denomination coinValue cents that can be 
//obtained from amount (a different variable) cents. amount has been 
//decreased by the value of the coins, that is, decreased by     
//returnedValue*coinValue.

到目前为止,这是我所拥有的,但我想我错过的更多可以有人帮我一把吗?
我也不认为使用双打而不是int。

So far this is what I have but I think I am missing more can somebody give me a hand? And I am also not suppose to use doubles instead int.

public class Assignment6{
   public static void main(String [] args){
   amount = (int)(Double.parseDouble(args[0])*100);

   System.out.println("Five: " + computeCoin(500));
   System.out.println("one: " + computeCoin(100) );
   System.out.println("Q : " + computeCoin(25) );
   System.out.println("D : " + computeCoin(10) );
   System.out.println("N : " + computeCoin(5) );
   System.out.println("P : " + computeCoin(1) );
}


推荐答案

public class Assignment6 {
    private static int amount = 0;
    public static void main(String[] args) {
        amount = (int)(Double.parseDouble(args[0])*100);
        System.out.println("Five: " + computeCoin(500));
        System.out.println("one: " + computeCoin(100) );
        System.out.println("Q : " + computeCoin(25) );
        System.out.println("D : " + computeCoin(10) );
        System.out.println("N : " + computeCoin(5) );
        System.out.println("P : " + computeCoin(1) );
    }

    public static int computeCoin(int cointValue) {
        int val = amount / cointValue;
        amount -= val * cointValue;
        return val;
    }
}

这里的诀窍在于 computeCoin 方法,并且事实上除法是整数除法,所以 val 将保持'最大值'给定值( coinValue )的硬币总数,其总值不超过金额

The trick here lies in the computeCoin method, and in the fact that the division is integer division, so val will hold the 'maximum' number of coins of the given value (coinValue) whose total value does not exceed amount.

这篇关于Java程序,告诉我们从1美分到99美分的任何变化金额的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆