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

C语言菱形图案程序最后循环出错,输出结果始终异常的问题排查

问题分析与修复方案

我一眼就瞅见问题所在啦——你程序里下半V形部分的那个循环,犯了个很容易踩的小坑:

在down V part的if (x > 1)代码块里,你写的是:

printf("%d", &w);

这里的&w是取变量w的内存地址,而不是w本身的数值。程序每次运行时,变量的内存地址可能会随机变化,这就导致你每次得到的输出都不一样,完全不符合预期!

你只需要把&w改成w,让printf打印变量w的实际值就可以解决这个问题。

修正后的完整代码

#include <stdio.h>
int main() {
    int n;
    printf("Enter the number upto which the pattern is to be printed \n ");
    scanf("%d", &n);
    /* Upside inverted V */
    for (int i = 1; i <= n; i++) {
        for (int j = 1; j <= n - i; j++) {
            printf(" ");
        }
        for (int k = 1; k <= i; k++) {
            printf("%d", k);
        }
        if (i > 1) {
            for (int l = i - 1; l > 0; l--) {
                printf("%d", l);
            }
        }
        printf("\n");
    }
    // down V part
    for (int x = n - 1; x >= 1; x--) {
        for (int y = n; y > x; y--) {
            printf(" ");
        }
        for (int z = 1; z <= x; z++) {
            printf("%d", z);
        }
        if (x > 1) {
            // 这里把&w改成了w
            for (int w = x - 1; w >= 1; w--) {
                printf("%d", w);
            }
        }
        printf("\n");
    }
    return 0;
}

测试示例

比如当你输入n=3时,修正后的程序会输出:

1
 121
12321
 121
  1

完全符合菱形图案的预期啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 13:22:38