方法 printPowersOf2 接受一个最大数作为参数,并打印从 2^0 到该最大数的每个 2 的幂。
printPowersOf2(3);输出 1 2 4 8 printPowersOf2(5);输出 1 2 4 8 16 32
我似乎无法找出要打印的正确代码。我必须使用循环和 *= 运算符。不允许上数学课。我知道这也很简单
这是我的代码
public class Chap3LabP2 {
public static void main(String[] args) {
printPowersof2(3);
printPowersof2(5);
printPowersof2(10);
printPowersof2(12);
}
public static void printPowersof2(int maxNum){
System.out.print("1" + " ");
for(int i = 1; i <= maxNum; i++){
System.out.print(i*2 + " ");
}
System.out.println("");
}
}
最佳答案
在循环之前设置 i = 2。循环体应该是(伪代码):
我 *= 2
打印我
关于java - 需要帮助打印二的幂,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21960597/