gpt4 book ai didi

java - Random.nextDouble 数学错误

转载 作者:行者123 更新时间:2023-11-29 08:49:47 25 4
gpt4 key购买 nike

我正在开发一款用于从银行账户存入和提取资金的小应用程序。该程序大部分运行良好,但我从一些带有大量尾随小数的交易中得到奇怪的输出。我随机生成应该只有 2 位小数的 double ,所以我不确定它们来自哪里。

C:\Users\Jon\Documents\Class\Java>java SavingsAccountTest
Balance: 62.0
Deposit Count: 0
Withdraw Count: 0
Annual Interest Rate: 0.09
Service Charges: 0.0
Active: false

Withdraw first, then deposit using
randomly generated amounts.

Balance: 62.0
Withrdaw: Deposit:
8.76 35.43

Your account is inactive due to: Insufficient Funds
***Unable to complete withdrawal.***

Balance: 97.43
Withrdaw: Deposit:

16.83 3.98


Balance: 84.58000000000001
Withrdaw: Deposit:
99.44 35.2

Your account is inactive due to: Insufficient Funds
***Unable to complete withdrawal.***

Press enter to continue.


C:\Users\Jon\Documents\Class\Java>

问题出在第二笔交易上,第三笔交易的余额为 84.58000000000001。

这是我的主类的代码。

import java.util.Random;
import java.util.Scanner;

public class SavingsAccountTest
{
public static void main(String[] args)
{
Random rand = new Random();

double[] depositArray = {(double)rand.nextInt(10001)/100,
(double)rand.nextInt(10001)/100,
(double)rand.nextInt(10001)/100};

double[] withdrawArray = {(double)rand.nextInt(10001)/100,
(double)rand.nextInt(10001)/100,
(double)rand.nextInt(10001)/100};

SavingsAccount account = new SavingsAccount((double)rand.nextInt(101),
(double)(rand.nextInt(10)+1)/100.0);

System.out.print(account.toString());

System.out.println("\n\n\tWithdraw first, then deposit using\n\trandomly generated amounts.");

for (int i = 0; i < 3; i++)
{
System.out.println("\nBalance: " + account.getBalance());
System.out.print("Withrdaw:\t\tDeposit:\n" +
withdrawArray[i] + "\t\t\t" + depositArray[i] + "\n\n");

account.withdraw(withdrawArray[i]);
account.deposit(depositArray[i]);
}

pause();
}

private static void pause()
{
Scanner keyboard = new Scanner(System.in);

System.out.print("\nPress enter to continue.");
keyboard.nextLine();
System.out.print("\n");
}
}

这是从 SavingsAccount 存款和取款的方法

public void withdraw(double amount)
{
if (this.active && amount <= super.balance)
super.withdraw(amount);

else
System.out.print("Your account is inactive due to: " +
"Insufficient Funds" + "\n***Unable to complete " +
"withdrawal.***\n");
}

public void deposit(double amount)
{
if (super.balance + amount >= 25.00)
{
this.active = true;
super.deposit(amount);
}

else
super.deposit(amount);
}

下面是 BankAccount 父类(super class)的存款和取款方法:

public void withdraw(double withdraw)
{
this.balance -= withdraw;
withdrawCount++;
}

public void deposit(double deposit)
{
this.balance += deposit;
depositCount++;
}

最佳答案

这是因为值是以二进制形式存储的。 84.58 无法用二进制准确表示,但可以接近。显然它能得到的最接近的是 84.58000000000001。要解决此问题,您可以使用 format or printf格式化输出..

关于java - Random.nextDouble 数学错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23346966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com