#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/