gpt4 book ai didi

c++ long double 精确打印所有数字

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:44:00 27 4
gpt4 key购买 nike

关于我的问题,我在这里看到了一篇帖子,但不明白,因为我是 C++ 的新手。我写了一个小脚本,它从用户那里获取一个数字,脚本打印出输入数字的阶乘。一旦我输入更大的数字,如 30,脚本不会打印出所有数字。输出就像 2.652528598 E+32 但是我想要的是确切的数字 265252859812191058636308480000000。有人可以解释如何以长 double 获取所有数字。提前致谢

最佳答案

您可以将输出流的精度设置为任何您想要的精度,以获得您想要的结果。

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

这是页面的摘录以及代码示例。

Get/Set floating-point decimal precision The floating-point precision determines the maximum number of digits to be written on insertion operations to express floating-point values. How this is interpreted depends on whether the floatfield format flag is set to a specific notation (either fixed or scientific) or it is unset (using the default notation, which is not necessarily equivalent to either fixed nor scientific).

Using the default floating-point notation, the precision field specifies the maximum number of meaningful digits to display in total counting both those before and those after the decimal point. Notice that it is not a minimum, and therefore it does not pad the displayed number with trailing zeros if the number can be displayed with less digits than the 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.

This decimal precision can also be modified using the parameterized manipulator setprecision.

// modify precision
#include <iostream> // std::cout, std::ios

int main () {
double f = 3.14159;
std::cout.unsetf ( std::ios::floatfield ); // floatfield not set
std::cout.precision(5);
std::cout << f << '\n';
std::cout.precision(10);
std::cout << f << '\n';
std::cout.setf( std::ios::fixed, std:: ios::floatfield ); // floatfield set to fixed
std::cout << f << '\n';
return 0;
}

可能的输出:

3.1416
3.14159
3.1415900000

Notice how the first number written is just 5 digits long, while the second is 6, but not more, even though the stream's precision is now 10. That is because precision with the default floatfield only specifies the maximum number of digits to be displayed, but not the minimum. The third number printed displays 10 digits after the decimal point because the floatfield format flag is in this case set to fixed.

关于c++ long double 精确打印所有数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31632753/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com