我正在尝试对程序中的镍币数量进行四舍五入(不再有镍币了)。因此,如果我输入 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 +"$" );
}
}
最佳答案
我建议将数字乘以十,并用Math.round()四舍五入,然后将其除以十。
1.46 * 10 = 14.6
Math.round(14.6) = 15
15 / 10 = 1.5
1.44 * 10 = 14.4
Math.round(14.4) = 14
14 / 10 = 1.4
这可以通过以下 lambda 来实现:
d -> Math.round(d * 10) / 10.0
指定 10.0
而不是 10
很重要,因为 Math.round()
返回一个 long
值,并且您不需要整数除法,而是 float 除法。
您可以在 this ideone snippet 上看到它的运行情况.
关于java - 获取零钱的程序(四舍五入帮助),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36942677/