当前位置: 动力学知识库 > 问答 > 编程问答 >

for loop - Trying to understand java code: Print powers of 2. How does it start from 2^0?

问题描述:

I have :

 public static void main(String[] args){

printPowersOf2(3);

printPowersOf2(10);

}

public static void printPowersOf2(int number){

int power = 1;

System.out.print(power + " ");

for(int i = 1; i <= number; i++){

power *= 2;

System.out.print(power + " ");

}

System.out.println();

}

}

and I get the needed output of

1 2 4 8

1 2 4 8 16 32 ...etc

but I don't understand how we got 1 (which is 2^0) if we didn't specify the 0 in any of the lines of code.

网友答案:

I guess it first prints the power 1 (number as is), and then goes starting with i =1. But how come then when it reaches 3 it prints 8 ...

网友答案:

The first time you call print, power is equal to one so all you would need to do is remove the first print statement before your for loop.

分享给朋友:
您可能感兴趣的文章:
随机阅读: