1. 程式人生 > 實用技巧 >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;
}

列印結果:

如果將負號去掉,則是下面的結果: