用3的幂填充一个数组

huangapple go评论132阅读模式
英文:

Fill an array with powers of 3

问题

public class Power {

    public static void main(String[] args) {
        
        int base = 3, exponent = 9;

        int[] result = new int[10];
        result[0] = 1;  // Initialize the first element of the array with 1
        
        System.out.println(result[0]);

        int i = 1;  // Start from the second element of the array
        while (exponent != 0)
        {
            result[i] = result[i - 1] * base;  // Multiply the previous element by the base and store in the current element
            --exponent;
            System.out.println(result[i]);
            i++;
        }
    }
}
英文:
public class Power {

    public static void main(String[] args) {
        
        int base = 3, exponent = 9;

        int[] result = new int[10];
        System.out.println(result);

        while (exponent != 0)
        {
            result * base = result;
            --exponent;
            System.out.println(result);
        }
    }
}

What I would like this code to do is be able to Multiply 1*3 to make 3, put it inside of the array, and multiply it again, and so on and so forth. Basically, it needs to output, 1 3 9 27 81 243 729 2187 6561 19683. How can I store it inside of the array, and also multiply it again?

答案1

得分: 0

你可以保留一个结果变量,并继续将其保存到一个数组中:

int index = 0;
int[] result = new int[10];
int current = 1;
for (int i = 0; i < result.length; ++i) {
    result[i] = current;
    current *= 3;
}
System.out.println(Arrays.asString(result));
英文:

You could keep a result variable and continue saving it to an array:

int index = 0;
int[] result = new int[10];
int current = 1;
for (int i = 0; i &lt; result.length; ++i) {
    result[i] = current;
    current *= 3;
}
System.out.println(Arrays.asString(result));

答案2

得分: 0

你的第一个问题是赋值语句需要将变量名放在左边,表达式放在右边;将 result * base = result; 替换为 result = result * base;

其次,result 是一个数组。你试图将它当作单个数字来处理。

第三,如果你想要填充一个数组,使用一个 for 循环,而不是你目前的方式:

final int base = 3;

final int[] result = new int[10];
result[0] = 1;

for (int i = 1; i < result.length; i++) {
    result[i] = result[i - 1] * base;
}
英文:

Your first problem is that assignments need the name on the left side, and the expression on the right side; replace result * base = result; by result = result * base;.

Secondly, result is an array. You’re trying to treat it as a single number.

Thirdly, if you want to fill an array, use a for loop instead of what you currently have:

final int base = 3;

final int[] result = new int[10];
result[0] = 1;

for (int i = 1; i &lt; result.length; i++) {
    result[i] = result[i - 1] * base;
}

huangapple
  • 本文由 发表于 2020年8月26日 00:27:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63583211.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定