简体   繁体   中英

Loop never starting

I am trying to write a small method which will calculate the exponent given a number and power (I know about math.pow I am just doing this for kicks). However the loop inside my method never starts and I cant figure out why. My code is below, all help appreciated.

public static void main(String[] args) {

int result = exponantCalculation(2, 3);

System.out.println(result);

}

public static int exponantCalculation(int number, int power) {
    for (int i = 1;i >= power;i++) {
        number = number * number;
    }
    return number;
}
  1. You've used the wrong comparison operator in the loop condition ( >= , should be <= or < — see other answers).

  2. Not sure, maybe this was intentional, BUT if the method is meant to calculate " number to the power of power ", then you're incorrectly squaring the result of the previous iteration . This will produce a much higher value that the number to the power of power . You need to introduce a new variable and multiply it with number in the loop, eg

     long result = 1; for (int i = 0; i < power; i++) { result *= number; // same as "result = result * number" } return result; 

    Minor note: I've intentionally used long type for the result, which can slightly defer the integer overflow problem for big values.

Condition inside for loop is wrong.

Since you are passing 3 as power in your method as parameter, i is initialized with 1 and then condition gets checked whether i>=power with is obviously not true in this case so your loop never starts.

Change

for (int i = 1;i >= power;i++)

to

for (int i = 1;i <= power;i++)

if you wish to calculate the power of any number, you can use following method

public static int exponantCalculation(int number, int power) {

      int result = 1;
      for (int i = 1;i <= power;i++) {
          result = result * number; 
      }  
      return result;
}

The for loop condition was wrong, but also you need to sotre the result in another variable:

 public static int exponantCalculation(int number, int power) {
    if(power == 0){
      return 1;
    }
    int result = 1;
    for (int i = 1;i <= power;i++) {
        result *= number;
    }
    return result;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM