java如何确定正方形的数学三角形的角度?
我需要修复底部显示的输出,我有输出正确数学值的代码 但它并没有输出我在下面提供的示例输出所期望的正确角度。(我知道这对大多数stack用户来说都很简单,但我是java初学者,这让我很困惑)。我还没有想到我能做些什么来解决这个问题,并把它放在正确的角度
说明:
-Write a program using a Scanner that asks the user for a number
n between 1 and 9 (inclusive).
-The program prints a triangle with n rows.
-The first row contains only the square of 1, and it is right-justified.
-The second row contains the square of 2 followed by the square of 1,
and is right justified.
-Subsequent rows include the squares of 3, 2, and 1, and then 4, 3, 2
and 1, and so forth until n rows are printed.
Assuming the user enters 4, the program prints the following triangle to the console
1
4 1
9 4 1
16 9 4 1
代码:
import java.util.Scanner;
public class Triangle {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Please enter a number between 1 and 9 inclusive:");
int n = scan.nextInt();
for (int i = 1 ; i <=n; i++) {
for (int j = n-i; j >=1; j--) {
System.out.print("");
}
for (int k = i; k <= n; k++ ) {
System.out.print(" " + i * i);
}
System.out.println(" ");
}
scan.close();
}
}
我的输出:
Please enter a number between 1 and 9 inclusive: 4
1 1 1 1
4 4 4
9 9
16
# 1 楼答案
TL;博士用笔和纸解决恼人的逻辑问题
解决这类问题的最简单方法是根据迭代的变量写出打印的位置。一个额外的变量
col
帮助我们跟踪当前列,该列与我们迭代的方向相反我们可以注意到,如果我们从右向左数列,这个数字正好对应于列的位置,平方
我们还可以注意到,空格的数量等于
n
——比当前行迭代少一个(因为它从0开始)抛开这些废话不谈,我们可以使用
String.format()
使两位数的输出为偶数# 2 楼答案
下面是一个简短的变体
以下是为输入9生成的输出: