zoukankan      html  css  js  c++  java
  • 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("
    ");
        }
        return 0;
    }
    

    打印结果:

    20201223163444

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

    20201223163510

  • 相关阅读:
    登录权限
    ajax搜索分页
    dos命令
    tp5单删
    MVC简易封装
    linux环境安装swoole
    nginx环境安装laravel404问题
    ABZ职业规划
    Yii安装curl
    SKU的概念和理解
  • 原文地址:https://www.cnblogs.com/fanlumaster/p/14179441.html
Copyright © 2011-2022 走看看