Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 两个数组的幂(n)_Java_Arrays - Fatal编程技术网

Java 两个数组的幂(n)

Java 两个数组的幂(n),java,arrays,Java,Arrays,我的代码不起作用 public static int[] powersOfTwoArray(int n) { int[] result = new int[n]; int i = 0; int power = 0; while (i <= n) { result[i] = power; power *= 2; } return result; } public static int[]powersOfTwoA

我的代码不起作用

public static int[] powersOfTwoArray(int n) {
    int[] result = new int[n];
    int i = 0;
    int power = 0;
    while (i <= n) {
        result[i] = power;
        power *= 2;
    }
    return result;
}
public static int[]powersOfTwoArray(int n){
int[]结果=新的int[n];
int i=0;
整数幂=0;

而(i你在做与零的乘法,每次都等于零。 试一试

int-power=1;

如果我误解了您的问题,请详细说明。

您的代码有三个问题,我在代码中已经提到:

public static int[] powersOfTwoArray(int n) 
{
    int[] result = new int[n+1];  // use "n+1" otherwise it will throw exception
    int i = 0;
    int power = 1;   // initiate power = 1, not power = 0;
    while (i <= n) 
    {
        result[i] = power;
        power *= 2;
        i++;        // increments "i" otherwise its an infinite loop
    }
    return result;
}
public static int[]powersOfTwoArray(int n)
{
int[]result=newint[n+1];//使用“n+1”,否则将引发异常
int i=0;
int power=1;//初始化power=1,而不是power=0;

虽然(谢谢,我犯了一个错误非常感谢!这非常有帮助!下次先试运行每行代码…然后你自己调试代码谢谢,我下次会这么做。