浮点数据类型减法给出错误的结果

时间:2019-06-12 21:09:46

标签: java math logic

我正在尝试创建一个银行帐户类,其中包含一个名为“ withdraw()”的方法以从名为“ balance”的变量中提取

当值为0.1f时,该方法给出的结果不正确,但是,如果将“ balance”的数据类型更改为double,则不会出现此问题。

有人可以向我解释为什么会这样吗?为什么这种情况会浮动而不是增加一倍?

这看似无关紧要的问题,但是,在数学方面,它会引起其他方法的问题,即使这样,程序也绝不能给出错误的结果。

... IN CLASS 'BankAccount'
private float balance;
...
public float withdraw(float value) {
        if (value <= balance) {
            value = (long) (value * 100);
            value = Math.abs(value) / 100;
            balance -= value;
            return value;
        }

        System.out.println("You have insufficient funds");
        return -1;
    }

    ... IN MAIN PROGRAMME
    BankAccount account = new BankAccount();
    account.setBalance(12444.234456f);

    System.out.println("Account balance = " + account.getBalance());
    System.out.println(account.getBalance() - 0.1f);
    System.out.println("New account balance = " + account.getBalance());
    ...


    System.out.println("Account balance = " + account.getBalance());. 
    Output: 21444.23 as expected. 
    (the setBalance() method removes unnecessary digits)

    System.out.println(account.getBalance() - 0.1f);
    System.out.println("New account balance = " + account.getBalance());
    Output 12444.131 not correct. 
    Expected output = 12444.13`enter code here`

0 个答案:

没有答案