C++ 如何使用cin读取double的整个值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13107632/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:58:07  来源:igfitidea点击:

How to read the entire value of a double using cin?

c++double

提问by freinn

long double m;
cout << "enter double: "; cin >> m;
cout << "m = " << m <<endl;

Input:

输入:

enter double: 1.546640625

输入双:1.546640625

Output:

输出:

m = 1.54664

米 = 1.54664

I have to convert into a binary with point, and when I read numbers like 2.359375000

我必须转换成带点的二进制,当我读到像 2.359375000 这样的数字时

Output:

输出:

m = 2.35938

米 = 2.35938

And it works, but I think the problem is the zero in 1.546640625

它有效,但我认为问题是 1.546640625 中的零

回答by Ivaylo Strandjev

You have read the whole value of the double. The problem is with the cout. It by default rounds the value to 6 digits after the decimal point.

您已经阅读了 double 的全部价值。问题出在 cout 上。默认情况下,它会将值四舍五入到小数点后的 6 位数字。

To set the precision cout uses, use setprecisionfrom <iomanip>:

要设置精度 cout 使用,请使用setprecisionfrom <iomanip>

#include <iostream>
#include <iomanip>

using namespace std;

int main() {
    long double d;
    cin >> d;
    cout << setprecision(10) << d << endl;
    return 0;
}