C语⾔printf左对齐和右对齐C 语⾔ printf("%d", n) 默认是左对齐,⽽如果是给定了数字宽度,如:
printf("%5d", n);
printf输出格式右对齐这个默认是右对齐,
⽽要改成左对齐,只需要加⼀个负号即可:
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;
}
打印结果:
如果将负号去掉,则是下⾯的结果: