java - 获取零钱的程序(四舍五入帮助)

标签 java rounding

我正在尝试对程序中的镍币数量进行四舍五入(不再有镍币了)。因此,如果我输入 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/

相关文章:

python - Pandas 读取具有浮点值的 csv 文件导致奇怪的舍入和小数位

c - 使用四舍五入的数据取平均值

java - 使用 Eclipse IDE 编辑 .settings/org.eclipse.wst.common.component

java - 何时在 Websphere Commerce 中使用访问 bean 或数据 bean?

java - Eclipse RCP : How to add a new element to a default Java dropdown menu in the toolbar(New Java Class)

java - 绑定(bind)属性不起作用

mysql - 格式和圆形mysql的区别

java - 这个问题的最佳设计模式

javascript - ViewModel 中的 double 在 JavaScript 数组中四舍五入为整数

.net - 如何在 .Net 中将小数四舍五入到小数点后两位?