模数据验证(.05增量,思考镍,硬币,四分之一等......)

时间:2017-10-23 13:18:00

标签: java validation modulus

处理一个简单的java程序,该程序只接受以0.05欧姆为增量的输入。当试图使用mod运算符进行数据验证时,我得到一些奇怪的,意想不到的结果:

        public static void takePayment(double itemCost){
    DecimalFormat df = new DecimalFormat("#.00");
    System.out.println(itemCost);
    Scanner input = new Scanner(System.in);
    System.out.println("Please insert $" + df.format(itemCost) + " into the machine");
    System.out.println("Type the amount you are inserting into the machine.");
    System.out.print("$");

    if (!input.hasNextDouble()){
        System.out.println("Please enter the amount inserted in X.XX format");
        takePayment(itemCost);
    }
    double amtInsert = 0;
    amtInsert = input.nextDouble(); 
    double remainder = 0;

    remainder = amtInsert %(0.05);
    System.out.println(remainder);

    if (remainder == 0)
    {
        System.out.println("works");
    }else{
        System.out.println("Invalid amount inserted, this machine only accepts Nickels, Dimes, Quarters, "
                + "1 dollar bills, and 5 dollar bills ");
        takePayment(itemCost);
    }


}

如果在函数中输入了诸如1.25的美元金额,则返回:

Please insert $1.25 into the machine
Type the amount you are inserting into the machine.
$1.25
0.04999999999999993
Invalid amount inserted, this machine only accepts  Nickels, Dimes, Quarters, 1 dollar bills, and 5 dollar bills.

有人可以解释为什么(1.25 % .05) = 0.04999999999999993

在阅读我的代码时请记住,我还没有完成其余的验证,我只关心目前的模数

0 个答案:

没有答案