我想圓我的計劃鎳的數量(有沒有硬幣了)。所以如果我輸入1.44,它應該是1.40,如果我有1.46,它應該是1.50。請幫忙!計劃得到改變(四捨五入幫助)
import java.util.Scanner;
public class MakingChange
{
private static Scanner scanner;
public static void main(String[] args)
{
scanner = new Scanner(System.in);
double amount = 0;
while (true) {
try {
amount = Double.parseDouble(scanner.nextLine());
break; // will only get to here if input was a double
} catch (NumberFormatException ignore) {
System.out.println("INVALID\r\n$");
}
}
//calculating amount of change in cents
int remainingAmount = (int)(amount * 100.00);
//toonies
int numberofToonies = (int) (remainingAmount/200.00);
remainingAmount = remainingAmount % 200;
//loonies
int numberofLoonies = (int) (remainingAmount/100.00);
remainingAmount = remainingAmount % 100;
//quarters
int numberofQuarters = (int)(remainingAmount/25.00);
remainingAmount = remainingAmount % 25;
//dimes
int numberofDimes = (int)(remainingAmount/10.00);
remainingAmount = remainingAmount % 10;
//nickels
int numberofNickels = (int)(remainingAmount/5.00);
remainingAmount = remainingAmount % 5;
//rounded value
numberofNickels=(int) (((amount -(numberofToonies * 2) - (numberofLoonies *1) - (numberofQuarters *0.25) - (numberofDimes * 0.10) - (numberofNickels * 0.05))+0.04)/0.05);
System.out.println(".*toonies:" + numberofToonies + ";" + " loonies:" + numberofLoonies + ";" + " quarters:" + numberofQuarters + ";" + " dimes:" + numberofDimes + ";" + " nickels:" + numberofNickels +"$");
}
}
那麼究竟如何不工作的代碼? –
*你可以做到這一點美國式的,如果你有1.44,那麼你得到1和技巧罐子得到0.44:P *也許您正在尋找['Math.round'](https://docs.oracle.com /javase/8/docs/api/java/lang/Math.html#round-double-)。還要注意的是,你不應該使用雙貨幣東西(用'BigDecimal'例如) – 2016-04-29 15:58:04
好,而沒有給我兩個五分,它只會給我一個...四捨五入關閉。此外,當我做得到兩個五分,我想讓它顯示1毛錢而不是兩個鎳 –