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

C语言数字垂直图案打印问题求助:函数无法生成完整图案

Fixing Your Vertical Number Pattern Function

Hey there! I’ve been stuck on pattern-printing bugs more times than I can count, so I feel your pain. Let’s get this vertical number pattern sorted out for you.

First, let’s ground this with the examples you mentioned:

Expected pattern for n=4:
1 2 3 4
1 2 3 4
1 2 3 4
1234

Expected pattern for n=5:
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
12345

From your description, your current code only spits out the first two lines of these patterns—let’s fix that.

Let’s Diagnose the Common Issue

Most often, this problem happens because the outer loop is limited to a fixed number of iterations (like 2) instead of matching the value of n. For example, if your original code looked something like this:

def print_vertical_pattern(n):
    # This loop only runs 2 times—why you only get 2 blocks!
    for i in range(2):
        for j in range(n):
            if j < i:
                print(" ", end="")
            print(j+1, end=" ")
        print()

Your current output for n=4 would be:

1 2 3 4
2 3 4

The Corrected Code

Here’s the revised version that generates the full pattern for any valid n:

def print_vertical_pattern(n):
    # Loop n times to create n lines total
    for i in range(n):
        line = ""
        # Add leading spaces for the current line
        line += " " * i
        # Add numbers with dynamic spacing
        for j in range(n):
            line += str(j + 1)
            # Only add a space if we haven't reached the "tight" section of the line
            if j > i:
                line += " "
        print(line)

Key Changes Explained:

  • Loop Range: Swapped range(2) for range(n) so we generate exactly n lines, one for each level of the pattern.
  • String Building: Constructing each line as a single string makes formatting more predictable than printing characters one by one.
  • Dynamic Spacing: We add leading spaces equal to the line number i, then only insert spaces between numbers if we’re still in the "spread out" part of the line (after the leading spaces, numbers start to tighten up).

Test Results

For n=4, this code outputs:

1   2   3   4
 1  2  3  4
   1 2 3 4
    1234

For n=5, it outputs:

1    2    3    4    5
 1   2   3   4   5
  1  2  3  4  5
   1 2 3 4 5
    12345

If your original code had a different root issue (like spacing logic instead of loop range), share your exact code and I can tweak this further!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:12:47