Search code examples
javamathexponent

This basic programme I wrote for exponents only works with integers - what did I do wrong?


I am building some basic programs as a way to practice different programming techniques. I thought I had written a programme to calculate exponents but it doesn't work correctly.

It works fine if I input integers ie. squared (2,5) but (2,4.5) doesn't work.

public static double squared(double a, double b) {
    double a1 = a;
    double sq = 0;      
    while (b > 1) {
        sq = a*a1;
        a =sq;
        b--;
    }
    return sq;
}

public static void main(String[] args) {
    System.out.println(squared(2,2));
}

Solution

  • Your program works as expect if b is an integer, because your code assumes b is an integer.

    The same result will be computed whether b is 4 ou 4.5, because both 0 and 0.5 are smaller than 1 (thus ending the loop).