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;
}

打印結果:

20201223163444

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

20201223163510


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM