[英]std::ofstream set precision for Floating point format
I need to write float type with 6 digit precision into file.我需要将具有 6 位精度的浮点类型写入文件。 This code does not work correctly as i expected:
这段代码没有像我预期的那样正常工作:
int main() {
std::ofstream ofs("1.txt", std::ofstream::out);
if (ofs.is_open() == false) {
std::cerr << "Couldn't open file... 1.txt" << std::endl;
return -1;
}
time_t t_start, t_end;
time(&t_start);
sleep(1);
time(&t_end);
float elapsed = difftime(t_end, t_start);
ofs<<"Elapsed time= " << std::setprecision(6) <<elapsed<< "(s)"<<std::endl;
ofs.close();
return 0;
}
Output:输出:
Elapsed time= 1(s)
any suggestion?有什么建议吗?
You have to use std::fixed
and std::setprecision
:你必须使用
std::fixed
和std::setprecision
:
ofs << "Elapsed time= " << std::fixed << std::setprecision(6)
<< elapsed << "(s)"
<< std::endl;
Further difftime()
returns a double not a float.进一步的
difftime()
返回一个 double 而不是一个浮点数。
double difftime(time_t time1, time_t time0);
The
difftime()
function returns the number of seconds elapsed between time time1 and time time0 , represented as a double .difftime()
函数返回time1和time0之间经过的秒数,表示为double 。
You need to insert std::fixed
into the stream if you want 0.000000
, along the lines of:如果需要
0.000000
,则需要将std::fixed
插入流中,如下所示:
ofs << "Elapsed time = "
<< std::setprecision(6) << std::fixed << elapsed << " (s)"
<< std::endl;
This gives you:这给你:
Elapsed time = 0.000000 (s)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.