0

I am beginner in Java. I am trying to find compound interest using this program. I don't want to use pre-defined power function. I am not getting correct output.

What's wrong in this code?

Thanks for help.

class Main {
    public static void main (String[] args) {
        int P=0,Tm=0;
        float R=0;
        Scanner sc=new Scanner(System.in);
        P=sc.nextInt();
        R=sc.nextFloat();
        Tm=sc.nextInt();
        System.out.print(P*power((1+R/100),Tm));
    }
    static float power(float R,int Tm)
    {
        float sum=R;
        for(int i=2;i<=Tm;i++)
        {
            sum*=R;
        }
        return sum;
    }
}
  • 1
    What is your expected output? for what value(s)? and what you are getting now? – Giorgi Tsiklauri Oct 13 '20 at 22:23
  • And what inputs would you expect to give to produce that expected output? – Kevin Anderson Oct 13 '20 at 22:25
  • @Giorgi Tsiklauri input : 1 99 1 Expected output : 2.96 My output : 3.96 – Mrugesh Raulji Oct 13 '20 at 22:33
  • @MrugeshRaulji why? how 1.99 should result in 2.96? based on what logic? maybe you can elaborate on that more in your question? otherwise, we can't guess it out of the blue. Also, please respect Java naming conventions and do NOT name your variables with first capital letter, like `This`. – Giorgi Tsiklauri Oct 13 '20 at 22:36
  • Also, you have 3 inputs.. – Giorgi Tsiklauri Oct 13 '20 at 22:43
  • 2
    First, verify that the `power` function works on ts own; it looks OK, but it never hurts to check. And second, 99% interest??? In many jurisdictions, that's a criminal offense (;->) But seriously, 1 _buckaroo_, invested at 99% interest per _timeunit_, for 1 _timeunit_, seems like it should only yield 1.99 _buckaroos_, not 2.96 and certainly not 3.96. – Kevin Anderson Oct 14 '20 at 07:41
  • As KevinAnderson mentioned, the expected output from `1 99 1` is `1.99` - and that is what your code gives me. You will get inaccurate results for some calculations because you are using [floating point math](https://stackoverflow.com/questions/588004/is-floating-point-math-broken/2607316#2607316). Use Java's [`BigDecimal`](https://stackoverflow.com/questions/3413448/double-vs-bigdecimal) instead. – andrewJames Oct 14 '20 at 18:00

0 Answers0