我的计算器代码问题-输出值不正确 这是我的代码,任何答复将不胜感激。
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();
}
}
最终值与初始值相同
答案 0 :(得分:5)
更改此:
double monthlyInterest = ((interestRate/100)*(1/12));
到
double monthlyInterest = (interestRate / 100) * (1.0 / 12.0);
您正在尝试在浮点上下文中进行整数除法,因此在monthlyInterest
中,您实际上是将interestRate / 100
与0相乘。
答案 1 :(得分:2)
用数字添加d
可以将它们转换为双精度并保留十进制值-
double monthlyInterest = ((interestRate/100d)*(1/12d));
如果对整数进行1/12
,则输出将为0
,而对于1/12d
,输出将为0.08333333333333333
此外,您可以去除多余的括号-
double monthlyInterest = (interestRate/100d)*(1/12d);
...
double number1 = monthlyInterest + 1;
...
double total = initialAmount * number2;