gpt4 book ai didi

java - 打印一个正方形三角形。如何镜像数字?

转载 作者:行者123 更新时间:2023-12-02 19:40:36 25 4
gpt4 key购买 nike

所以,我已经在这个实验室上为我的编程课工作了一段时间,到目前为止,我认为我走在正确的道路上。

但是,我不太确定如何镜像这些数字。基本上,我的代码只打印三角形的上半部分。不管怎样,这是给我们的实际任务:

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
9 4 1
4 1
1

For full credit, each column should be 3 characters wide and the values should be right justified.

现在这是我到目前为止为我的代码编写的内容:

import java.util.Scanner;
public class lab6 {
public static void main(String[] args) {
Scanner kybd = new Scanner(System.in);
System.out.println(
"Enter a number that is between 1 and 9 (inclusive): ");

// this is the value that the user will enter for # of rows
int rows = kybd.nextInt();

for (int i = rows; i > 0; i--) {
for (int j = rows; j > 0; j--)
System.out.print((rows - j + 1) < i ?
" " : String.format("%3d", j * j));
System.out.println();
}
}
}

这就是当我输入 4 时代码打印的内容:

Enter a number that is between 1 and 9 (inclusive): 
4
1
4 1
9 4 1
16 9 4 1

正如你所看到的,我只能打印出三角形的上半部分。我一直在尝试弄清楚如何镜像它,但我似乎无法弄清楚。我在这个网站上寻求帮助,并在整个互联网上寻求帮助,但我似乎无法做到这一点。

最佳答案

答案是:

public static void main(String... args) {
Scanner kybd = new Scanner(System.in);
System.out.println("Enter a number that is between 1 and 9 (inclusive): ");

int rows = kybd.nextInt(); // this is the value that the user will enter for # of rows

for (int i = -rows + 1; i < rows; i++) {
for (int j = -rows; j < 0; j++)
System.out.print(abs(i) > j + rows ? " " : String.format("%3d", j * j));
System.out.println();
}
}

尝试将其视为如何找到三个线性函数之间的点(笛卡尔)(位于两者之间的三角形面积):

y = 0 // in loops i is y and j is x
y = x + 4
y = -x -4

这是 4 的示例结果:

enter image description here

还有9:

enter image description here

关于java - 打印一个正方形三角形。如何镜像数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60256717/

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