3 回答
TA贡献1842条经验 获得超12个赞
实现这样重复的通常方法是使用for循环:
System.out.println("The following is a table of values, showing numbers 0 - 10 and their squares and cubes.");
System.out.printf("%s%s%s%n", "Number ", "Square ", "Cube");
for (int num = 0; num <= 10; num++) {
System.out.printf("%d \t %d \t %d%n", num, num * num, num * num * num);
}
TA贡献1155条经验 获得超0个赞
您正在寻找的解决方案是如何使代码和变量可重用。一种方法是使用函数,尽管您可能还没有学习到这一点。然后,您将使用 for 循环将数字 1 到 10 输入到您的函数中以获得所需的输出。
public static int NumberSquared(int number)
{
return number*number;
}
public static int NumberCubed(int number)
{
return number*number*number;
}
public static void main(String[] args)
{
for(int i=0; i <= 10; i++)
{
System.out.println("Number " + i + " Square: " + NumberSquared(i) + " Cube: " + NumberCubed(i));
}
}
TA贡献1873条经验 获得超9个赞
逻辑是错误的,你必须在更新之后计算平方和立方体numbList,所以你必须使用任何循环或递归来做到这一点,但我更喜欢有两种方法返回 int 值,一个用于计算平方,另一个用于立方体
public class NewMain {
public static void main(String[] args) {
int numbList = 0;
System.out.println("The following is a table of values, showing numbers 0 - 10 and their squares and cubes.");
System.out.printf("%s%s%s%n", "Number ", "Square ", "Cube");
//
System.out.printf("%d \t %d \t %d%n", numbList = 0, squareOfNumber(numbList), cubeOfNumber(numbList));
System.out.printf("%d \t %d \t %d%n", numbList = 1, squareOfNumber(numbList), cubeOfNumber(numbList));
System.out.printf("%d \t %d \t %d%n", numbList = 2, squareOfNumber(numbList), cubeOfNumber(numbList));
System.out.printf("%d \t %d \t %d%n", numbList = 3, squareOfNumber(numbList), cubeOfNumber(numbList));
System.out.printf("%d \t %d \t %d%n", numbList = 4, squareOfNumber(numbList), cubeOfNumber(numbList));
System.out.printf("%d \t %d \t %d%n", numbList = 5, squareOfNumber(numbList), cubeOfNumber(numbList));
System.out.printf("%d \t %d \t %d%n", numbList = 6, squareOfNumber(numbList), cubeOfNumber(numbList));
System.out.printf("%d \t %d \t %d%n", numbList = 7, squareOfNumber(numbList), cubeOfNumber(numbList));
System.out.printf("%d \t %d \t %d%n", numbList = 8, squareOfNumber(numbList), cubeOfNumber(numbList));
System.out.printf("%d \t %d \t %d%n", numbList = 9, squareOfNumber(numbList), cubeOfNumber(numbList));
System.out.printf("%d \t %d \t %d%n", numbList = 10, squareOfNumber(numbList), cubeOfNumber(numbList));
}
public static int squareOfNumber(int num) {
return num*num;
}
public static int cubeOfNumber(int num) {
return num*num*num;
}
}
for循环你可以应用上面相同的逻辑
for(int i=0; i<=10; i++) {
System.out.printf("%d \t %d \t %d%n", i, i*i, i*i*i);
}
你也可以使用Math.pow()
nt intResult = (int) Math.pow(2, 3);
该方法将 2 提高到 3 的幂并返回结果
添加回答
举报