Calculating a value a raised to an exponent b

2

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

 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 is giving this error but I have no idea how to fix it.

    
asked by anonymous 16.09.2015 / 07:31

1 answer

3

You should check if the exponent is negative, and if it is, reverse the base and change the sign of the exponent:

if(expoente < 0) {
    expoente *= -1;
    base = 1 / base; 
}
while(expoente != 0) {
...
    
16.09.2015 / 07:55