c++ - 对齐输出中的小数位?

标签 c++ c++14

#include <iomanip>
#include <cmath>
#include <iostream>
using namespace std;


int main() {
    //
    //HERE IS THE ISSUE
    //set precision to 3 decimals
    cout<<fixed;
    //printing the final pressure of the gas
    cout <<setw(20)<<left<<setfill('.')<<"Equation #01"<<"Ideal Gas Law(Chemistry): "<<setw(5)<<setprecision(3)<<gaslawPressure<<" atm" 
<<endl;

    //printing the calculated distance
    cout <<setw(20)<<left<<setfill('.')<<"Equation #02"<<"Distance Formula(Math): "<<setw(5)<<setprecision(3)<<pointDistance<<endl;
    return 0;
}

给出的输出:

Equation #01........Ideal Gas Law(Chemistry): 1.641 atm
Equation #02........Distance Formula(Math): 30.017

期望的输出:

Equation #01........Ideal Gas Law(Chemistry):    1.641 atm
Equation #02........Distance Formula(Math)  :   30.017

我还需要让冒号对齐。

最佳答案

您必须根据您的文本在不同部分放置适当的 setw 以及左对齐

1)第一部分

setw(20)<<left<<setfill('.')<<"Equation #01" 

2) 第二部分假设它的长度约为 30

setw(30)<<left<<setfill(' ')<<"Ideal Gas Law(Chemistry)"

3) 对齐冒号:

setw(3)<<left<<setfill(' ')<<":"

4)值部分

setw(5)<<std::left<<setprecision(3)<<gaslawPressure<<" atm"



#include <iomanip>
#include <cmath>
#include <iostream>
using namespace std;


int main() {
    //
    //HERE IS THE ISSUE
    //set precision to 3 decimals
    auto gaslawPressure = 1.641;
    auto pointDistance = 30.017;

    cout<<fixed;
    //printing the final pressure of the gas
    cout <<setw(20)<<left<<setfill('.')<<"Equation #01"<<setw(30)<<left<<setfill(' ')<<"Ideal Gas Law(Chemistry)"<<setw(3)<<left<<setfill(' ')<<":"<<setw(5)<<std::left<<setprecision(3)<<gaslawPressure<<" atm"<<endl;

    //printing the calculated distance
    cout <<std::left<<setw(20)<<left<<setfill('.')<<"Equation #02"<<setw(30)<<left<<setfill(' ')<<"Distance Formula(Math)"<<setw(3)<<left<<setfill(' ')<<":"<<setw(5)<<setprecision(3)<<pointDistance<<endl;
    return 0;
}

输出

Equation #01........Ideal Gas Law(Chemistry)      :  1.641 atm
Equation #02........Distance Formula(Math)        :  30.017
Program ended with exit code: 0

关于c++ - 对齐输出中的小数位?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54227411/

相关文章:

c++ - 在 for_each 中使用变换 boost fusion

c++ - 什么时候应该使用 C++14 自动返回类型推导?

c++ - 使用容器转发引用

c++ - 范围何时会包含在 C++ 标准中?

c++ - 具有可变模板模板参数的方法的部分特化

c++ - 是否有(更)合理的方法来确定 ostream 所针对的终端的宽度?

c++ - 如何找出Qt中托盘系统栏的位置?

c++ - 几乎为空的 .exe 文件的重量是由什么造成的?

android - __attribute__((used)) 在将静态库链接到共享对象时无效(android gcc 4.8)

c++ - 来自右值的非常量引用的无效初始化