gpt4 book ai didi

java - 如何使用for循环在java中创建一个后向三角形

转载 作者:行者123 更新时间:2023-12-01 16:57:55 26 4
gpt4 key购买 nike

我需要制作一个如下所示的三角形

       *
**
***
****
*****
******
*******

目前我有一个看起来像这样的工作

*
**
***
****
*****
******
*******

使用循环:

public static void standard(int n)
{
for(int x = 1; x <= n; x++)
{
for(int c = 1; c <= x; c++)
{
System.out.print("*");
}
System.out.println();
}
}

我该如何完成这项工作

       *
**
***
****
*****
******
*******

这是我的尝试:

public static void backward(int n) 
{
for(int x = 7; x <= n; x++)
{
for(int y = 1; y >= x; y--)
{
if (x >= y)
{
System.out.print("*");
}
else
{
System.out.print("");
}
}
System.out.println();
}
}

最佳答案

在每一行打印n字符:如果索引 c < n - x ,打印空格,否则打印星号:

for (int x = 1; x <= n; x++) {
for (int c = 0; c < n; c++)
System.out.print(c < n - x ? ' ' : '*');
System.out.println();
}

输出(n = 6):

     *
**
***
****
*****
******
<小时/>

关于java - 如何使用for循环在java中创建一个后向三角形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30239266/

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