Std :: cout floating point

I am using visual studio 2015 to print two floating numbers:

double d1 = 1.5;
double d2 = 123456.789;

std::cout << "value1: " << d1 << std::endl;
std::cout << "value2: " << d2 << std::endl;

std::cout << "maximum number of significant decimal digits (value1): " << -std::log10(std::nextafter(d1, std::numeric_limits<double>::max()) - d1) << std::endl;
std::cout << "maximum number of significant decimal digits (value2): " << -std::log10(std::nextafter(d2, std::numeric_limits<double>::max()) - d2) << std::endl;

The following is printed:

value1: 1.5
value2: 123457
maximum number of significant decimal digits (value1): 15.6536
maximum number of significant decimal digits (value2): 10.8371

Why is 123457 printed for value 123456.789? The ANSI C ++ spec allows you to display anything for floating numbers when std :: cout is used without std :: setprecision ()?

+4
source share
3 answers

Rounding is due to the C ++ standard, which can be seen by writing std::cout<<std::cout.precision();

The output screen will display 6, which indicates that the default number of digits to be printed by the cout operator is 6. That's why it automatically rounds the floating number to 6 digits.

+1
source

, , ++ , , , . , operator<<(double), , " num_put - cout << some_float_value.

- , print("%g", value); [ 88 n3337 ++ , printf ++]. , %.16g, , setprecision(16).

+1

, , , standard iostream ++. , : -

printf ("%f\n", d2);

std::cout, std::setprecision, %g %f printf. : -

std::cout << std::setprecision(10) << "value2: " << d2 << std::endl;

But if you do not like this method and you use C ++ 11 (& onwards), you can also write: -

std::cout << "value2: " << std::to_string(d2) << std::endl;

This will give you the same result as printf ("%f\n", d2);.

A much better method is to undo the rounding that occurs in std::coutusing std::fixed: -

#include <iostream>
#include <iomanip>
int main()
{
    std::cout << std::fixed;
    double d = 123456.789;
    std::cout << d;
    return 0;
}

Exit: -

123456.789000

So, I think your problem is resolved.

0
source

Source: https://habr.com/ru/post/1616936/


All Articles