gpt4 book ai didi

java - 无法找出java中伪代码转换的数据

转载 作者:行者123 更新时间:2023-12-02 01:38:48 26 4
gpt4 key购买 nike

int month = 1;                                              
int balance = 500;
int totalpaid = 0;
double interest;
while (balance > 100);
{
balance = balance - 100;
interest = (balance * 0.1);
balance = totalpaid + interest;
totalpaid = totalpaid + 100;
month = month + 1;
}
System.out.println ("you paid" + "," + totalpaid);
System.out.println ("it took you" + "," + month + "months");

我本质上是想找出这段代码中的错误,错误是当我尝试将总付款和利息加在一起时出现的。

最佳答案

balance 是一个 int,您正在尝试将 totalpaid (int) 和 interest (double) 添加在一起。你不能这样做,你必须对相同的数据类型进行操作。 理论上,您可以将结果转换为 int,错误就会消失:

  balance = (int) totalpaid + interest;                                               

但不要这样做。使用 intdouble 处理货币并不是正确的方法,因为它不准确,并且可能会导致浮点错误。请改用 BigDecimal

 public static void main(String[] args) {
int month = 1;
BigDecimal balance = BigDecimal.valueOf(500);
BigDecimal totalpaid = BigDecimal.valueOf(0);
BigDecimal interest;
while (balance.compareTo(BigDecimal.valueOf(100)) > 0)
{
balance = balance.subtract(BigDecimal.valueOf(100));
interest = (balance.multiply(BigDecimal.valueOf(0.1)));
balance = (totalpaid.add(interest));
totalpaid = totalpaid.add(BigDecimal.valueOf(100));
month = month + 1;
}
System.out.println ("you paid" + "," + totalpaid.toString());
System.out.println ("it took you" + "," + month + "months");
}

关于java - 无法找出java中伪代码转换的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54772970/

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