普通网友 2016-11-03 15:18 采纳率: 0%
浏览 2476
已采纳

小白,一个矩阵弄不出来,求大神

要弄一个比如输入3就输出 1 2 4
3 5 7
6 8 9 这样的类似矩阵
求代码

  • 写回答

13条回答 默认 最新

  • threenewbee 2016-11-03 16:32
    关注
     #include <stdio.h>
    #include <stdlib.h>
    int main()
    {
        int n = 3;
        int * p = (int *)malloc(sizeof(int) * n * n);
        int cx = 0, cy = 0;
        int i;
        for (i = 1; i <= n * n; i++)
        {
            p[cy * n + cx] = i;
            if (cy == n - 1) { cy = cx + 1; cx = n - 1; continue; }
            if (cx == 0) { cx = cy + 1; cy = 0; continue; }
            cx--;
            cy++;
        }
        for (i = 0; i < n * n; i++)
        {
            printf("%d\t", p[i]);
            if (i % n == n - 1) printf("\n");
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(12条)

报告相同问题?