我必须编写一个Java程序,告诉从1美分到99美分的零钱要赠送多少硬币。例如,如果金额为86美分,则输出将类似于以下内容:
86美分可以分为3个季度,1个角钱和1便士。
使用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来代替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
)的“最大”硬币数,其总值不超过amount
。关于java - Java程序,告诉您从1美分到99美分的零钱要发出什么样的硬币,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11143304/