简体   繁体   中英

C++ Double values precision during file output

I have the following code in c++

ofstream myfile;
    myfile.open ("promise.txt");

    for( int rating=lowerLimit; rating<=upperLimit; rating++ )
    {
        promise = promisePVTable->getPromise(durationTable, rating, duration);

        myfile << "Promise  " << rating << " : " << promise << "\n";
        hurdle = rc_min(1, (promise - 1) / promise);

        hurdles.push_back(hurdle);
    }

Every time i output the value of promise it truncates the value to 4 or 5 decimals in the output thought the actual value is 16 digits in decimals.How can i change the precision of double value during file output.

Thanks

Use std::setprecision

#include <iomanip>
//....

myfile << "Promise  " 
       << rating 
       << " : " 
       << std::setprecision(16) << promise 
       << "\n";

Your ofstream (or actually the io_base, from which ofstream is derived from) has a "precision" function to set the decimal precision for the next floating-point value.

See: http://www.cplusplus.com/reference/ios/ios_base/precision/

So you have to write:

myfile << "Promise  " << rating << " : ";
myfile.precision(16);
myfile << promise << "\n";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM