针对std :: ofstream的浮点格式的C++设置精度

问题描述:

我需要将具有6位精度的浮点类型写入文件。 此代码不能正常工作,因为我预计:针对std :: ofstream的浮点格式的C++设置精度

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; 
} 

输出:

Elapsed time= 1(s) 

什么建议吗?

你必须使用std::fixedstd::setprecision

ofs << "Elapsed time= " << std::fixed << std::setprecision(6) 
    << elapsed << "(s)" 
    << std::endl; 

而且difftime()回报的双重不浮动。

double difftime(time_t time1, time_t time0);

difftime()函数返回的时间之间经过的时间1 时间时间0/1/2秒的数量,表示为双

你需要插入std::fixed到流,如果你想0.000000,沿着线:

ofs << "Elapsed time = " 
    << std::setprecision(6) << std::fixed << elapsed << " (s)" 
    << std::endl; 

这给了你:

Elapsed time = 0.000000 (s)