gpt4 book ai didi

Java 程序,它告诉从 1 美分到 99 美分的任何数量的零钱都应该给出什么硬币

转载 作者:行者123 更新时间:2023-11-30 07:25:02 24 4
gpt4 key购买 nike

我必须编写一个 Java 程序来告诉从 1 美分到 99 美分的任何数量的零钱都应该分发什么硬币。例如,如果金额为 86 美分,则输出将类似于以下内容:

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

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

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.

到目前为止,这就是我所拥有的,但我想我还缺少更多,有人可以帮助我吗?而且我也不应该使用 double 而不是整数。

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 将保留 ' maximum' 给定值 (coinValue) 的硬币数量,其总值不超过 amount

关于Java 程序,它告诉从 1 美分到 99 美分的任何数量的零钱都应该给出什么硬币,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11143304/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com