介绍C++中如何格式化输出浮点数。
控制浮点数输出格式需要包含iomanip头文件。
使用fixed来控制输出的浮点数的小数位是固定的。可参考http://en.cppreference.com/w/cpp/io/manip/fixed
使用right和left来控制输出的对其位置。
使用setw来控制后面一个数据占用多少个单位宽度。
#include <iostream>
#include <iomanip>
using namespace std;
int main(int argc, char** argv){
double salary = 0.;
double tax_percent = 0.01;
cout << "input Milk's salary please : ";
cin >> salary;
cout << std::fixed;
cout << std::setprecision(2);
cout << std::left << setw(15) << "Name";
cout << std::right << setw(15) << "Salary";
cout << std::right << setw(15) << "tax";
cout << endl;
cout << std::left << setw(15) << "Milk";
cout << std::right << setw(15) << salary;
cout << std::right << setw(15) << salary*tax_percent;
cout << endl;
return EXIT_SUCCESS;
}