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.
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
is8
, but2^-3
is1/8
).– mgibsonbr