gpt4 book ai didi

java - 程序算力为2

转载 作者:行者123 更新时间:2023-11-29 10:06:55 24 4
gpt4 key购买 nike

我正在编写一个简单的程序来计算 2 的次方。用户将输入他们想要计算 2 的次方的次数,假设用户输入 4,我的程序将返回 2、4、8, 16.这是代码

import java.util.Scanner;

public class PowersOf2

{

public static void main(String[] args)

{

int numPowersOf2;
//How many powers of 2 to compute

int nextPowerOf2 = 1;
//Current power of 2

int exponent = 0;

//Exponent for current power of 2 -- this

//also serves as a counter for the loop

Scanner scan = new Scanner(System.in);

System.out.println("How many powers of 2 would you like printed?");
numPowersOf2 = scan.nextInt();

//print a message saying how many powers of 2 will be printed
//initialize exponent -- the first thing printed is 2 to the what?

System.out.println("Here are the first " + numPowersOf2 + " power of 2");


while (exponent<numPowersOf2)
{
//print out current power of 2

nextPowerOf2=nextPowerOf2*2;

exponent++;

System.out.println(nextPowerOf2);
//find next power of 2 -- how do you get this from the last one?

//increment exponent
}
}
}

如果我想让它从 0 开始,首先说 2^0=1,那么如果用户输入 4,它会返回 1,2,4,8 而不是 2,4,8,16。我该如何修改它才能得到它?

最佳答案

2n == (1 << n); 0 <= n < 32

关于java - 程序算力为2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5222966/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com