Home > Software engineering >  Method output giving wrong output
Method output giving wrong output

Time:11-28

public class Pow {

    public double getAnswer(double a, double b) {

        double b2 = 0;

        if (b > 0) {
            for (int i = 1; i < b; i  ) {
                a = a * a;
            }
            return a;
        } else if (b < 0) {
            int c = 0;
            while (c > b) {
                a = a * a;
                c--;
            }
            b2 = 1 / a;
        }
        return b2;
    }
}

I need the second part of my method to return the value of a negative power(i.e. 5^-2 = .04), but the output is always 0. The first part of the method works fine from what I have tested. I do have the last curly braces but they just wouldn't fit in the text box on here. Any help/suggestions would be much appreciated!

CodePudding user response:

Running your code does not produce 0 as a result, but there is a bug.

a = a * a squares the number every iteration, so an will be calculated as: a2n-1.

Try accumulating the multiplication in a different variable:

double b2 = 0;
double result = 1;

if (b > 0) {
    for (int i = 1; i <= b; i  ) {
        result *= a;
    }
    return result;
} else if (b < 0) {
    int c = 0;
    while (c > b) {
        result *= a;
        c--;
    }
    b2 = 1 / result;
}
return b2;

CodePudding user response:

public class Pow {

    public double getAnswer(double a, double b) {

        double b2 = 0;

        if (b > 0) {
            for (int i = 1; i < b; i  ) {
                a = a * a;
            }
            return a;
        } else if (b < 0) {
            return getAnswer(a, -b);
        }
        return 1; // b is 0
    }

Your algorithm for (b < 0) was wrong. If b < 0, the calculation is 1 / a^(-b).

Why your parameter b is of type double? What if b is 2.5? I suggest to change the type of b to int or you have to change your algorithm.

CodePudding user response:

As Bohemian♦ said

a = a * a;

squares a each time.

What we want is for a (the base) to be multiplied by itself b (the power) times.

Since the only difference between a to the power of b and a to the power of (-b) is that the latter is the 1 / the former, we can use quite nearly the same code for both negative and positive exponents.

Code:

public double getAnswer(double a, double b) {//a is the base, b is the power

    double a2 = 1;
    double b2 = 0;

    if (b > 0) {//for positive powers
        for (int i = 0; i < b; i  ) {//a needs to be multiplied by itself (b) times
            a2 = a2 * a;
        }
        return a2;
    }
    else if (b < 0) {//for negative powers 
        for (int i = 0; i < -b; i  ) {//a still needs to be multiplied by itself (-b) times, but since b is negative, we increment up to the opposite of b
            a2 = a2 * a;
        }
        return 1 / a2;//finally, since the power (b) is negative, we need to return 1 / (a2)
    }
}
  • Related