【发布时间】:2014-05-17 21:26:05
【问题描述】:
我刚刚完成了一个代码,允许用户输入两个数字(a 和 b),然后程序会计算 a^b。这段代码必须在不使用Math.pow 方法的情况下完成。
我必须将 1-10 到 1-3 的幂的结果保存在一个数组中。当我运行我的代码 4 存储在所有。这是我在 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在第二部分有什么作用。 -
是的,我将它们用于 toPowerOf 方法,但我不确定
-
如果您不确定变量,请不要使用它们。
标签: java arrays for-loop methods nested-loops