Java 利息计算器
我的计算器代码有问题-输出值不正确 这是我的代码,任何回复都将不胜感激Java 利息计算器,java,Java,我的计算器代码有问题-输出值不正确 这是我的代码,任何回复都将不胜感激 import java.util.Scanner; public class Savings { public static void main(String[] args) { Scanner console = new Scanner(System.in); //ask for initial amount System.out.print("What is the ini
import java.util.Scanner;
public class Savings {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
//ask for initial amount
System.out.print("What is the initial savings amount? ");
double initialAmount = console.nextDouble();
// ask for number of months
System.out.print("What is the number of months to save? ");
int months = console.nextInt();
//ask for interest rate
System.out.print("What is the annual interest rate? ");
double interestRate = console.nextDouble();
//calculate total
double monthlyInterest = ((interestRate/100)*(1/12));
double number1 = (monthlyInterest + 1);
double number2 = Math.pow(number1, months);
double total = (initialAmount*number2);
System.out.println("$" + initialAmount + ", saved for " + months + " months at " + interestRate + "% will be valued at $" + total);
console.close();
}
}
最终值与初始值相同更改此项:
double monthlyInterest = ((interestRate/100)*(1/12));
到
您试图在浮点上下文中进行整数除法,因此在monthlyInterest
中,您实际上是将interestRate/100
与0相乘。更改此项:
double monthlyInterest = ((interestRate/100)*(1/12));
到
您试图在浮点上下文中进行整数除法,因此在
monthlyInterest
中,您实际上是将interestRate/100
与0相乘。将d
与数字相加,以将它们转换为双精度并保留十进制值,这样做-
double monthlyInterest = ((interestRate/100d)*(1/12d));
如果使用整数执行1/12
,则输出将为0
,但使用1/12d
则输出将为0.08333
另外,您可以去掉额外的括号-
double monthlyInterest = (interestRate/100d)*(1/12d);
...
double number1 = monthlyInterest + 1;
...
double total = initialAmount * number2;
将
d
与数字相加,将其转换为双精度,并保留十进制值,方法如下-
double monthlyInterest = ((interestRate/100d)*(1/12d));
如果使用整数执行1/12
,则输出将为0
,但使用1/12d
则输出将为0.08333
另外,您可以去掉额外的括号-
double monthlyInterest = (interestRate/100d)*(1/12d);
...
double number1 = monthlyInterest + 1;
...
double total = initialAmount * number2;
请给我们一个输入和输出以及预期输出的示例输入为25000,输出为25530.31,时间和利息分别为24个月和1.05请给我们一个输入和输出以及预期输出的示例输入为25000,输出为25530.31,时间和利息分别为24个月和1.05