Calculation of a high value to an exponent b

Asked

Viewed 1,072 times

2

I must create an algorithm that calculates a value a high to a exponent b. It is an exercise that cannot use Math.pow. I did the algorithm and when I put negative exponent the result.

 public static void main(String[] args) {
        Scanner ler = new Scanner(System.in);
        int base, expoente, calculo=1;
        System.out.println("Informe a base:");
        base = ler.nextInt();
        System.out.println("Informe o expoente:");
        expoente = ler.nextInt();
        while(expoente!=0) {
            calculo=base*calculo;
            expoente--;
        }
        System.out.println(calculo);
    }
}

I know it’s because of the while that’s giving this mistake but I have no idea how to fix it.

  • 1

    If the exponent is positive, you have to decrease it to zero, but if the exponent is negative you have to ingrow it to zero. Test if expoente is greater or less than zero, and act accordingly (do not forget also that the calculation itself is different for negative exponents - 2^3 is 8, but 2^-3 is 1/8).

1 answer

3


You should check if the exponent is negative, and if it is, reverse the base and change the exponent’s signal:

if(expoente < 0) {
    expoente *= -1;
    base = 1 / base; 
}
while(expoente != 0) {
...
  • 3

    +1 just remembering that for this to work so much base how much calculo have to be doubles, no ints (otherwise any base larger than one will turn zero).

  • Thanks for the help.

Browser other questions tagged

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