What is the role of **std::setprecision()** without **std::fixed** in c++?

前端 未结 4 984
陌清茗
陌清茗 2021-02-04 15:52

As shown in the tutorial http://www.cplusplus.com/reference/iomanip/setprecision/

// setprecision example
#include      // std::cout, std::fixed
         


        
相关标签:
4条回答
  • 2021-02-04 16:04

    This is because "When floatfield is set to fixed, floating-point values are written using fixed-point notation: the value is represented with exactly as many digits in the decimal part as specified by the precision field (precision) and with no exponent part." ref. http://www.cplusplus.com/reference/ios/fixed/

    0 讨论(0)
  • 2021-02-04 16:12

    According to http://en.cppreference.com/w/cpp/io/ios_base/precision, the precision decides how many digits are printed, not how many digits after the floating point are printed:

    std::ios_base::precision

    Manages the precision (i.e. how many digits are generated) of floating point output

    This explains the rounding.

    Yes, using std::fixed will change the interpretation of the floatfield precision. According to http://www.cplusplus.com/reference/ios/ios_base/precision/:

    In both the fixed and scientific notations, the precision field specifies exactly how many digits to display after the decimal point, even if this includes trailing decimal zeros. The digits before the decimal point are not relevant for the precision in this case.

    0 讨论(0)
  • 2021-02-04 16:22

    The meaning of precision depends on whether fixed, scientific or default format is used. For fixed format, it's the number of digits after the decimal point. For scientific, it is, too - but there's always exactly one digit before the point; the exponent is used to shift the decimal point into position. For default format, precision specifies the total number of digits printed (roughly; it's a bit more complicated).

    For details, see http://en.cppreference.com/w/cpp/io/c/fprintf , in particular the description of %f, %e and %g format specifiers (for fixed, scientific and default format, correspondingly). std::cout << f is specified to behave as if printf("%.<precision><format>", f) is called (to the first approximation; the reality is, again, a bit more complicated, but the details are not relevant to the issue at hand), where <precision> is the number specified by setprecision, and <format> is one of f, e or g.

    0 讨论(0)
  • 2021-02-04 16:22

    Behaviour of std::setprecision() differs depending on the chosen formatting.

    std::fixed make std::setprecision() refer to how many digits are printed after the decimal point. Before you change the default formatting to std::fixed, std::defaultfloat is set, and std::setprecision() sets the total number of digits to be printed, including the ones both before and after the decimal point.

    Compare:

    http://www.cplusplus.com/reference/ios/defaultfloat/

    http://www.cplusplus.com/reference/ios/fixed/

    0 讨论(0)
提交回复
热议问题