我想创建一个金字塔并将每个数字乘以2,直到达到中间然后除以2,如下例所示。
然而,在编写我的代码后,我无法将数字加倍(i * 2),然后一旦到达中心,它就会除以2,直到它变为1
我的输出:
package question5;
public class Pyramid {
public static void main(String[] args) {
int x = 5;
int rowCount = 1;
System.out.println("Here Is Your Pyramid");
//Implementing the logic
for (int i = x; i > 0; i--)
{
//Printing i*2 spaces at the beginning of each row
for (int j = 1; j <= i*2; j++)
{
System.out.print(" ");
}
//Printing j value where j value will be from 1 to rowCount
for (int j = 1; j <= rowCount; j++)
{
System.out.print(j+" ");
}
//Printing j value where j value will be from rowCount-1 to 1
for (int j = rowCount-1; j >= 1; j--)
{
System.out.print(j+" ");
}
System.out.println();
//Incrementing the rowCount
rowCount++;
}
}
}
答案 0 :(得分:2)
这是有效的...您可以使用math.pow方法。
public class test {
public static void main(String[] args) {
int x = 5;
int rowCount = 1;
System.out.println("Here Is Your Pyramid");
//Implementing the logic
for (int i = x; i > 0; i--)
{
//Printing i*2 spaces at the beginning of each row
for (int j = 1; j <= i*2; j++)
{
System.out.print(" ");
}
//Printing j value where j value will be from 1 to rowCount
for (int j = 0; j <= rowCount-1; j++)
{
System.out.printf("%2d", (int)Math.pow(2, j));
}
//Printing j value where j value will be from rowCount-1 to 1
for (int j = rowCount-1; j >= 1; j--)
{
System.out.printf("%2d", (int)Math.pow(2, j-1));
}
System.out.println();
//Incrementing the rowCount
rowCount++;
}
}
}
答案 1 :(得分:0)
现在您正在输出Math.floor(Math.random()*3) - 1
,一个从j
到1
的号码。您想要输出 2 j-1 ,这很容易:5
。
您还需要右键调整数字。然后您的打印声明变为:
1 << (j - 1)