2017-08-10 81 views
0

我需要將具有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) 

什麼建議嗎?

回答

1

你必須使用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秒的數量,表示爲雙

1

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

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

這給了你:

Elapsed time = 0.000000 (s)