我有一个float值列表,我想cout用2位小数打印它们.
例如:
10.900 should be printed as 10.90
1.000 should be printed as 1.00
122.345 should be printed as 122.34
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
(setprecision似乎没有帮助.)
bed*_*uin 163
有了<iomanip>,你可以使用std::fixed和std::setprecision
这是一个例子
#include <iostream>
#include <iomanip>
int main()
{
double d = 122.345;
std::cout << std::fixed;
std::cout << std::setprecision(2);
std::cout << d;
}
Run Code Online (Sandbox Code Playgroud)
你会得到输出
122.34
Run Code Online (Sandbox Code Playgroud)
Vus*_*sak 39
你几乎就在那里,需要使用std :: fixed,请参考http://www.cplusplus.com/reference/iostream/manipulators/fixed/
#include <iostream>
#include <iomanip>
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)
小智 9
#include<stdio.h>
int main()
{
double d=15.6464545347;
printf("%0.2lf",d);
}
Run Code Online (Sandbox Code Playgroud)
简化已接受的答案
简化示例:
#include <iostream>
#include <iomanip>
int main()
{
double d = 122.345;
std::cout << std::fixed << std::setprecision(2) << d;
}
Run Code Online (Sandbox Code Playgroud)
你会得到输出
122.34
Run Code Online (Sandbox Code Playgroud)
参考:
我在编码比赛中遇到了类似的问题,这就是我处理它的方法。将所有双精度值的精度设置为 2
首先添加标头以使用set precision
#include <iomanip>
然后在我们的main中添加如下代码
double answer=5.9999;
double answer2=5.0000;
cout<<setprecision(2)<<fixed;
cout <<answer << endl;
cout <<answer2 << endl;
Run Code Online (Sandbox Code Playgroud)
输出:
5.99
5.00
Run Code Online (Sandbox Code Playgroud)
你需要使用fixed来写入5.00,这就是为什么你的输出不会是5.00。
我想要整数时遇到一个整数问题。
为了完整性而重写:
#include <iostream>
#include <iomanip>
int main()
{
// floating point formatting example
double d = 122.345;
cout << std::fixed << std::setprecision(2) << d << endl;
// Output: 122.34
// integer formatting example
int i = 122;
cout << std::fixed << std::setprecision(2) << double(i) << endl;
// Output: 122.00
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
400919 次 |
| 最近记录: |