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

如何用C语言单循环逐字符打印指定图案(禁止使用数组)

用C语言单循环打印指定图案的实现

首先分析图案的规律(共6行):

  • 第i行(i从1到6):
    • 先输出i个小写字母'a'
    • 接着输出i-1个小写字母'b'(第1行无b)
    • 然后输出i-2个星号'*'(前2行无*)
    • 再输出一个大写字母:从'A'开始,每行递增2(A→C→E→G→I→K)
    • 最后输出换行符

以下是满足要求的单循环实现代码,每次循环仅输出一个字符,不使用数组:

#include <stdio.h>

int main() {
    int current_line = 1;   // 当前处理的行号(1-6)
    int step = 0;           // 当前行内的输出步骤:0=a,1=b,2=*,3=大写字母,4=换行
    int char_count = 0;     // 当前步骤已输出的字符数

    while (1) {
        if (step == 0) {
            putchar('a');
            char_count++;
            if (char_count == current_line) {
                char_count = 0;
                step = 1;
            }
        } else if (step == 1) {
            if (current_line == 1) {
                step = 3;
                continue;
            }
            putchar('b');
            char_count++;
            if (char_count == current_line - 1) {
                char_count = 0;
                step = 2;
            }
        } else if (step == 2) {
            if (current_line < 3) {
                step = 3;
                continue;
            }
            putchar('*');
            char_count++;
            if (char_count == current_line - 2) {
                char_count = 0;
                step = 3;
            }
        } else if (step == 3) {
            putchar('A' + 2 * (current_line - 1));
            step = 4;
        } else if (step == 4) {
            putchar('\n');
            current_line++;
            step = 0;
            char_count = 0;
            if (current_line > 6) {
                break;
            }
        }
    }
    return 0;
}

代码说明

  • 用current_line跟踪当前要打印的行,从1到6;
  • step变量控制当前行内的输出阶段,按a→b→*→大写字母→换行的顺序切换;
  • char_count记录当前阶段已输出的字符数,达到对应数量后自动切换到下一个阶段;
  • 循环会在所有6行处理完成后退出,全程仅使用一个while循环,每次迭代输出一个字符。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 05:17:12