You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何按行列打印右侧对齐的星号,每行星号数等于当前行数?

Fixing Right-Aligned Asterisk Pattern Printing

Got it, let's sort out this pattern issue! The core problem here is that you're only outputting one asterisk per line, instead of scaling the number of asterisks to match the current row number. Let's break down how to fix this.

First, clarify the pattern we need

For each row i (from 1 to 10):

  • Leading spaces: 10 - i (so row 1 has 9 spaces, row 2 has 8, ..., row 10 has 0)
  • Asterisks: exactly i (row 1 has 1 *, row 2 has 2 *, ..., row 10 has 10 *)

Solution with code examples

Let's cover two common languages to make this concrete:

Python

Python makes this super clean with string multiplication—no need for nested loops if you don't want them:

for row in range(1, 11):
    # Print the leading spaces first
    print(" " * (10 - row), end="")
    # Now print the asterisks, count equals current row number
    print("*" * row)

The key line here is "*" * row—this generates a string of row asterisks, which is the piece you were missing earlier!

Java

If you're using a language that doesn't support string multiplication directly, nested loops work perfectly:

public class RightAlignedStars {
    public static void main(String[] args) {
        // Outer loop controls each row
        for (int row = 1; row <= 10; row++) {
            // First inner loop: print leading spaces
            for (int spaceCount = 1; spaceCount <= 10 - row; spaceCount++) {
                System.out.print(" ");
            }
            // Second inner loop: print asterisks matching row number
            for (int starCount = 1; starCount <= row; starCount++) {
                System.out.print("*");
            }
            // Move to the next line after each row
            System.out.println();
        }
    }
}

Here, the second inner loop runs exactly row times, printing one asterisk each time—this ensures the count increases with each row.

Why your original code wasn't working

You were printing one asterisk per line regardless of the row number. By adding the logic to print row number of asterisks (either via string multiplication or a second loop), you'll get the right-aligned, increasing pattern you want.

内容的提问来源于stack exchange,提问作者user3740970

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:44:37