有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java复利公式不起作用,在main方法和second方法中输出奇怪的数字(没有给我正确的答案)

是的,我以前问过同样代码的问题,但更多的问题出现了,我似乎无法解决,开始复利公式是打印出奇怪的代码数。还有线路系统。出来println(化合物);在main中,该方法不起作用,因为“无法将复合解析为变量错误”),所以我无法打印它

import java.io.*;

class cexample {
    public static double squared(double x){
        return x*x;
    } 

    public static void main(String[] args)   throws IOException {
        System.out.println(balance(0.0, 0.0,1.0));
        System.out.println(balance);
    }

    static public double balance(double principal, double rate, double years) throws IOException{
        double amount = 0;
        String input;
        String input2;
        years = 1;
        BufferedReader myInput = new BufferedReader (new InputStreamReader (System.in));
        System.out.print("How much would you like to take out? ");
        input = myInput.readLine ();
        principal = Double.parseDouble (input);        
        System.out.print("Enter the interest rate: ");
        input2 = myInput.readLine ();
        rate = Double.parseDouble (input2);
        System.out.println("Now, enter the amount of years (1-10)");
        input = myInput.readLine ();
        years = Double.parseDouble (input);  
        for (int i = 0; i < years; i++) {
            // equation, M = P *( 1+ rate) * years^2
            amount = principal * (1 + rate) *( squared(years));
            //amount += principal;
        }
        System.out.println("The amount is " + amount);
        return amount; //- principal;
    }
}

共 (3) 个答案

  1. # 1 楼答案

    复利的计算公式是

    principal * (1+(rate/compounding periods) ^ (years / compounding periods)
    

    在您的情况下,复利期为1

    另一种计算方法是

    for(# of years)
      principal *= 1+rate
    

    你在做这两件事,另外还要计算年数,虽然我不知道你是从哪里得到这个想法的

  2. # 2 楼答案

    这行给您带来了问题,因为balance是一个方法。返回并重新阅读my answer on your previous question。看起来你只是复制了我给你的部分代码,而没有阅读或理解它。你需要确保你在做你认为你在做的事情

    你总是得到0作为结果(正如我在对上一个问题的评论中已经解释过的),因为你在一年中通过了1,而你的for循环从1开始,所以你从来没有实际计算过任何东西

  3. # 3 楼答案

    我不是真正的java专家,但我会使用数学函数,这应该可以完成以下工作:

    import java.lang.Math;
    
    P * Math.pow((1 + r), (years/period))