概览
我相信这对在座的大多数人来说都是一个简单的问题,但我一直在努力解决一个小间距问题,希望我能向更有经验的人学习。我需要制作一个类似于下图的三角形。您可以看到无论长度如何,数字都正确对齐。
Enter the number of lines: 8
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
1 2 4 8 16 32 64 32 16 8 4 2 1
1 2 4 8 16 32 64 128 64 32 16 8 4 2 1
我的代码
这是我目前所拥有的。它不是最漂亮的,但它似乎至少给了我正确的值。
import java.util.Scanner;
public class Pyramid2
{
public static void main(String[] args)
{
int i, j, k, l, a;
//Create a Scanner object
Scanner in = new Scanner (System.in);
//Prompt the user to enter number of rows in pyramid
System.out.print("Enter number of rows: ");
int rows = in.nextInt();
a = rows;
//Variables to determine length
int length = ("" + rows).length();
String str = " %" + length + "s";
//Logic
for (i = 1; i <= rows; i++)
{
for (j = a; j > 0; j--)
{
System.out.printf(str, " ");
}
for (j = 1; j <= (2*rows); j++)
{
if (j == (rows+1))
{
continue;
}
if (j < (rows+1))
{
k = j;
}
else
{
k = ((2*rows)-j+1);
}
if (k >= (rows+1-i))
{
l = (int)Math.pow(2, (i+k-rows-1));
String str1 = "" + l;
System.out.printf(str, str1);
}
}
a--;
System.out.println();
}
}
}
我的结果
这是选择 6 行时的控制台输出。一切看起来都很好,直到第 5 行出现一个 2 位数字 (16)。正确对齐结果的有效方法有哪些?
Enter number of rows: 6
1
1 2 1
1 2 4 2 1
1 2 4 8 4 2 1
1 2 4 8 16 8 4 2 1
1 2 4 8 16 32 16 8 4 2 1
最佳答案
你计算length
作为 rows
中的位数, 但必须是三角形中最大数的位数。
例如对于 rows = 6
, 最大的数字是 32
, 所以 length
应该是 2
.
对于 rows = 8
, 最大的数字是 128
, 所以 length
应该是 3
.
最大的数字是 2行,在 Java 中表示 1 << rows
, 所以改变 length
计算到:
int length = ("" + (1 << rows)).length();
您还在左侧添加了过多的空格。
将代码改成这样:
a = rows - 1;
关于Java - 关于 2 三角形幂的简单格式化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48464691/