用3的幂填充一个数组

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

Fill an array with powers of 3

问题

  1. public class Power {
  2. public static void main(String[] args) {
  3. int base = 3, exponent = 9;
  4. int[] result = new int[10];
  5. result[0] = 1; // Initialize the first element of the array with 1
  6. System.out.println(result[0]);
  7. int i = 1; // Start from the second element of the array
  8. while (exponent != 0)
  9. {
  10. result[i] = result[i - 1] * base; // Multiply the previous element by the base and store in the current element
  11. --exponent;
  12. System.out.println(result[i]);
  13. i++;
  14. }
  15. }
  16. }
英文:
  1. public class Power {
  2. public static void main(String[] args) {
  3. int base = 3, exponent = 9;
  4. int[] result = new int[10];
  5. System.out.println(result);
  6. while (exponent != 0)
  7. {
  8. result * base = result;
  9. --exponent;
  10. System.out.println(result);
  11. }
  12. }
  13. }

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

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

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

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

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

答案2

得分: 0

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

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

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

  1. final int base = 3;
  2. final int[] result = new int[10];
  3. result[0] = 1;
  4. for (int i = 1; i < result.length; i++) {
  5. result[i] = result[i - 1] * base;
  6. }
英文:

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:

  1. final int base = 3;
  2. final int[] result = new int[10];
  3. result[0] = 1;
  4. for (int i = 1; i &lt; result.length; i++) {
  5. result[i] = result[i - 1] * base;
  6. }

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:

确定