How to do exponentiation in Java?

Asked

Viewed 5,333 times

6

I’m trying to make a accrual of compound interest and I have this code that follows until the moment.

public class ExDesafio_Aula1 {
        public static void main(String[]args){
            double investimento = 5000.00;
            double juros = 0.01;

            double valorFinal = investimento * (1 + juros) * 12;
            System.out.println(valorFinal);
    }
}

The problem is that at the end of the account, it should raise the value between parentheses by 12, not multiply it.

How to solve this problem?

2 answers

9

Try to use Math.pow:

public class ExDesafio_Aula1 {
    public static void main(String[] args) {
        double investimento = 5000.00;
        double juros = 0.01;

        double valorFinal = investimento * Math.pow(1 + juros, 12);
        System.out.println(valorFinal);
    }
}

See here working on ideone.

  • I recently made a calculation where my variables were all integers (result = Math.Pow (base, exponent)), and when compiling I was returned a type incompatibility error, because the result variable was declared as integer. I solved it by declaring it a double. My variable that will receive the result of a calculation done with Math.Pow always has to be double ? Even if the result is integer ?

  • @Snickers See this other answer: https://answall.com/a/304447/132

-2

The difference is that if you use ** the answer is a real value and if you use the result is an integer.

8 ** 3 The answer would be 512.00

8 3 The answer would be 512

8.5 ** 3 The answer would be 614,125

8.5 3 The answer would be 614

Radiance by the power Index - root | radicando = radicando elevated to 1/Indice Example: 512 cubic root = 512 high 1/3 -> 512 * *(1 / 3)

  • 1

    This answer makes no sense. The language in question is Java where there is no arithmetic operator ** and the operator ^ is the binary or. See here and here.

  • Yes actually I saw this way of using potency in another language and believed that java had something similar. I must remove this logic stated above???

  • Correct the information provided, making it useful for java users. See [Ask] and also see Community FAQ.

  • *Errata: Veja [Answer]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.