2013-10-03 39 views
0

我想在最后写一个do while while循环来编写这个复利兴趣程序,我无法弄清楚如何打印出最终的金额。Java中的复合兴趣程序

这里是我到目前为止的代码:

public static void main(String[] args) { 
    double amount; 
    double rate; 
    double year; 

    System.out.println("This program, with user input, computes interest.\n" + 
    "It allows for multiple computations.\n" + 
    "User will input initial cost, interest rate and number of years."); 

    Scanner keyboard = new Scanner(System.in); 

    System.out.println("What is the initial cost?"); 
    amount = keyboard.nextDouble(); 

    System.out.println("What is the interest rate?"); 
    rate = keyboard.nextDouble(); 
    rate = rate/100; 

    System.out.println("How many years?"); 
    year = keyboard.nextInt(); 


    for (int x = 1; x < year; x++){ 
     amount = amount * Math.pow(1.0 + rate, year); 
       } 
    System.out.println("For " + year + " years an initial " + amount + " cost compounded at a rate of " + rate + " will grow to " + amount); 


    String go = "n"; 
    do{ 
     System.out.println("Continue Y/N"); 
     go = keyboard.nextLine(); 
    }while (go.equals("Y") || go.equals("y")); 
} 

}

回答

1

麻烦的是,amount = amount * Math.pow(1.0 + rate, year);。您将用计算的金额覆盖原始金额。您需要一个单独的值来保持计算的值,同时仍保持原始值。

所以:

double finalAmount = amount * Math.pow(1.0 + rate, year); 
在输出

然后:

System.out.println("For " + year + " years an initial " + amount + 
    " cost compounded at a rate of " + rate + " will grow to " + finalAmount); 

编辑:另外,您也可以节省一条线,一个变量,只是做了计算内联,因为这样的:

System.out.println("For " + year + " years an initial " + amount + 
    " cost compounded at a rate of " + rate + " will grow to " + 
    (amount * Math.pow(1.0 + rate, year))); 
+0

做内联计算固定一切!以另一种方式做它是给我“finalAmount的未知变量”的错误 –

+0

谢谢! :)你们真棒 –

+0

@MicahCalamosca哦,对不起。为了做到这一点,使用'finalAmount',你需要声明'finalAmount'变量,就像你声明所有其他变量一样。无论如何,我很高兴你的工作。如果您使用我的解决方案,请接受它作为答案。谢谢。 – nhgrif