gpt4 book ai didi

java - For 循环创建一个数组,该数组存储一个数字的另一个数字的幂的值

转载 作者:太空宇宙 更新时间:2023-11-04 14:58:43 25 4
gpt4 key购买 nike

我刚刚完成了一个代码,允许用户输入两个数字(a 和 b),程序将执行 a^b 的计算。此代码必须在不使用 Math.pow 方法的情况下完成。

我必须将 1-10 的 1-3 次方的结果保存在数组中。当我运行我的代码 4 时,它存储在 all.这是我在 javadoc 中的整个代码就是问题。

/**
* a. Declare a two dimensional double array with 10 rows and 3 columns. b.
* Store the results from the question above in a 2D array. c. Use a nested loop
* to print this array out and also add up all the array values. d. Print this
* sum to the screen. 7. Calling public static methods from another class: a.
* Write as second class called MyTestProgram which has only a main method in
* it. b. In this main method make use of the toPowerOf method defined in
* BlueTest2 to calculate 73 (7 cubed or 7*7*7) and write the result to the
* screen.
*
*/

public class BlueTest2 {
public static void main(String[] args) {
int result = toPowerOf(20, 5);
System.out.println("The power of these numbers is: " + result);
{
for (int i = 1; i <= 10; i++) {
for (int j = 1; j <= 3; j++) {
int loopResult = toPowerOf(i, j);
System.out.println(i + " to the power of " + j + " is: "
+ loopResult);
}
}

}
{
int[][] array3d = new int [10] [3];
for (int i = 1; i <= array3d.length; i++)
{
for (int j = 1; j <= array3d[0].length; j++)
{
int loopResult = toPowerOf(i, j);
array3d[i][j] = loopResult;
System.out.println("The variable here is: " + array3d[i][j]);
}
}
}
}

public static int toPowerOf(int a, int b) {
int t = a;
int result = a;
for (int i = 1; i < b; i++) {
t = t * a;
result = t;
}
return result;
}
}

我的新更改仅针对我的主要方法的第二部分

       {
int[][] array3d = new int [10] [3];
for (int i = 1; i <= array3d.length; i++)
{
for (int j = 1; j <= array3d[0].length; j++)
{
int loopResult = toPowerOf(i, j);
array3d[i][j] = loopResult;
System.out.println("The variable here is: " + array3d[i][j]);
}
}
}

最佳答案

问题是您在每次迭代中计算 a^b,并且将 ab 初始化为 1。因此,每次迭代计算 (i+1)^(j+1) 会更好:

for (int i = 0; i < array2d.length; i++) {
for (int j = 0; j < array2d[0].length; j++) {
//int a = 1;
//a++;
//int b = 1;
//b++;
int loopResult = toPowerOf(i+1, j+1);
array2d[i][j] = loopResult;
System.out.println("The variable at " + i + " " + j
+ " is: " + array2d[i][j]);
}
}

关于java - For 循环创建一个数组,该数组存储一个数字的另一个数字的幂的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22881874/

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