简体   繁体   English

循环从不开始

[英]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). 我正在尝试编写一个小方法来计算给定数字和幂的指数(我知道math.pow我只是为了踢)。 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 . 不知道,也许这是故意的,但如果该方法是指计算“ number到的功率power ”,那么你错误地现蕾前一次迭代的结果 This will produce a much higher value that the number to the power of power . 这将产生一个更高的值,该number到的电源power You need to introduce a new variable and multiply it with number in the loop, eg 您需要引入一个新变量并将其与循环中的number相乘,例如

     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. 小调:我故意使用long类型作为结果,这可以稍微推迟整数溢出问题的大值。

Condition inside for loop is wrong. for loop条件是错误的。

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. 既然你是路过3power在你的方法作为参数, i被初始化为1 ,然后条件被检查是否i>=power与显然是不正确的在这种情况下让你的循环永远不会发生。

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: for循环条件错误,但您还需要将结果放在另一个变量中:

 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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