因此,我已经在这个实验室上为我的编程课工作了一段时间,到目前为止,我认为我走在正确的轨道上。
但是,我不太确定如何反映这些数字。基本上,我的代码只打印三角形的上半部分。无论如何,这是给我们的实际任务:
使用a编写一个程序Scanner
要求用户输入号码n
之间1
and 9
(包括的)。该程序打印一个三角形n
行。第一行仅包含 1 的平方,并且是右对齐的。第二行包含 2 的平方,后跟 1 的平方,并且右对齐。后续行包括 3、2 和 1 的平方,然后是 4、3、2 和 1,依此类推,直到n
打印行。
假设用户输入4
,程序将以下三角形打印到控制台:
1
4 1
9 4 1
16 9 4 1
9 4 1
4 1
1
对于满分,每一栏都应该是3
字符宽并且这些值应该是右对齐的。
现在这是我到目前为止为我的代码编写的内容:
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 的示例结果:
And 9:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)