首页 > 解决方案 > C ++ cout将双精度对齐到2并右对齐

问题描述

如何将代码对齐到右侧的 3 个位置而不是默认的左侧?

10.23   
100.23

 10.23 ----------Like this
100.23  


double test = 10.2345;
double test2 =100.2345;

std::cout << std::setprecision(2) << std::fixed << test << '\n' << test2 << std::endl;

标签: c++formatting

解决方案


首先使用设置输出的宽度,然后使用std::cout.width(num);设置输出到右侧std::right,如下所示:

#include <iostream>
#include <iomanip>

int main()
{
    std::cout.width(6);
    std::cout << std::right << 10.23 << std::endl;
    std::cout << std::right << 10.453;

    return 0;
}

推荐阅读