C 语言 printf 左对齐和右对齐

时间:2020-12-23
本文章向大家介绍C 语言 printf 左对齐和右对齐,主要包括C 语言 printf 左对齐和右对齐使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

C 语言 printf("%d", n) 默认是左对齐,而如果是给定了数字宽度,如:

printf("%5d", n);

这个默认是右对齐

而要改成左对齐,只需要加一个负号即可:

printf("%-5d", n);

示例:

#include <stdio.h>
#include <string.h>
#define maxn 20
int a[maxn][maxn];

int main()
{
    int n, x, y, tot = 0;
    scanf("%d", &n);
    memset(a, 0, sizeof(a));
    tot = a[x = 0][y = n - 1] = 1;
    while (tot < n * n)
    {
        while (x + 1 < n && !a[x + 1][y]) a[++x][y] = ++tot; // 向下
        while (y - 1 >= 0 && !a[x][y - 1]) a[x][--y] = ++tot; // 向左
        while (x - 1 >= 0 && !a[x - 1][y]) a[--x][y] = ++tot; // 向上
        while (y + 1 < n && !a[x][y + 1]) a[x][++y] = ++tot; // 向右
    }
    for (x = 0; x < n; x++)
    {
        for (y = 0; y < n; y++)
        {
            printf("%-3d", a[x][y]); // - 表示左对齐,默认是右对齐
        }
        printf("\n");
    }
    return 0;
}

打印结果:

如果将负号去掉,则是下面的结果:

原文地址:https://www.cnblogs.com/fanlumaster/p/14179441.html