hfh*_*hc2 6 c++ iostream string-formatting
我需要一些使用C++流输出格式化的帮助.我想打印固定小数点和最多2个尾随位置的数字.我尝试过以下方法:
#include <iostream>
#include <iomanip>
using namespace std;
int main(int argc, char **argv)
{
float testme[] = { 0.12345, 1.2345, 12.345, 123.45, 1234.5, 12345 };
std::cout << std::setprecision(2) << std::fixed;
for(int i = 0; i < 6; ++i)
{
std::cout << testme[i] << std::endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
0.12
1.23
12.35
123.45
1234.50
12345.00
Run Code Online (Sandbox Code Playgroud)
但我想拥有
0.12
1.23
12.35
123.45
1234.5
12345
Run Code Online (Sandbox Code Playgroud)
我可以在不使用额外的字符串操作的情
这可行(http://ideone.com/CFcVhu),但它并不那么漂亮......
#include <iostream>
#include <iomanip>
using namespace std;
int main(int argc, char **argv)
{
float testme[] = { 0.12345, 1.2345, 12.345, 123.45, 1234.5, 12345 };
//std::cout << std::setprecision(2) << std::fixed;
for(int i = 0; i < 6; ++i)
{
std::cout << ((int)(testme[i]*100.0))/100.0f << std::endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)