double truncates at 7 characters of output

2020-03-05 06:53发布

double fat = 0.2654654645486684646846865584656566554566556564654654899866223625564668186456564564664564;
cout<<fat<<endl;

results in:

0.265465

Should it be 7 charcters longer? I thought that a double could hold more than that?

I also get the same result of a "long double".

标签: c++
5条回答
别忘想泡老子
2楼-- · 2020-03-05 06:54

There are two issues here:

  • you only get 7 significant figures because your cout stream is defaulting to a precision of 7, as the other answers state you can increase this to std::numeric_limits<double>::digits10

  • double can only store a fixed amount of precision anyway so most of the digits assigned to fat will be thrown away (on most machines you will get up to 15 significant figures into a double)

查看更多
Anthone
3楼-- · 2020-03-05 06:59

You're just seeing the default precision used by an iostream.

To improve things, use std::setprecision().

const int max_digits = std::numeric_limits<double>::digits10;

std::cout << std::setprecision(max_digits) << fat << std::endl;
查看更多
▲ chillily
4楼-- · 2020-03-05 07:01

Use std::setprecision(std::numeric_limits<double>::digits10) for maximum precision

std::cout << std::setprecision(std::numeric_limits<double>::digits10) << fat << std::endl;
查看更多
仙女界的扛把子
5楼-- · 2020-03-05 07:03

The problem is with cout, which defaults to a certain number of decimal places. You can set cout's precision and then add a fixed to give you the precision you need

cout.precision(15);
cout << fixed << fat << endl;
查看更多
贼婆χ
6楼-- · 2020-03-05 07:17

use cout.precision().
or, you can also use std::numeric_limits< double > and #include <limits> to get the maximum precision of a float or double..
see this SO post.

查看更多
登录 后发表回答