[英]Issues with C++ Precision
我看到许多帖子谈到了如何在C ++中以给定的精度显示数字,但是我想知道是否有一种方法可以显示非重复数字,例如x.0和setprecision指定的宽度重复数字方法?
If you knew in advance whether the number you want to print exhibits a recurring decimal expansion, then you could simply issue an statement along the lines of: 如果您事先知道要打印的数字是否显示重复的十进制扩展名,则可以简单地通过以下方式发出声明:
if is_recurring:
print using expanded format
else
print using fixed format
I imagine you do not know in advance. 我想你事先不知道。 And the computer cannot, in general, know it either.
而且计算机通常也不会知道。
How would it test whether a few decimals (about 15 if you are using double precision) represent a recurring decimal? 如何测试几个小数点(如果使用双精度,则大约为15)代表一个重复的小数点?
Furthermore, how would you like to print it? 此外,您想如何打印? Take, for instance, the classical example:
以经典示例为例:
3227 / 555 = 5.814414414414414
How should I print it? 我应该如何打印? Like this?
像这样?
5.8144
or like that? 还是那样?
5.8144
***
It seems like a very difficult problem to address in general. 一般而言,这似乎是一个非常困难的问题。
It sounds like what you really want is to trim trailing zeroes. 听起来您真正想要的是修剪尾随零。 The machine doesn't know whether a number is really a "recurring number," which is just a fancy name for a rational number whose denominator is relatively prime from the numeric base, because floating point math is not based on rational numbers.
机器不知道数字是否真的是“递归数字”,这只是分母相对于数字基数为质数的有理数的奇特名称,因为浮点数学不是基于有理数的。
As Adam mentioned, the default output style is already to omit trailing zeroes. 正如亚当(Adam)所述,默认的输出样式已经是省略尾随零。 This hasn't much to do with math;
这与数学无关。 it's just deleting the characters from the end of the string.
它只是从字符串末尾删除字符。
In terms of the Standard, the ios_base::fixed
and ios_base::scientific
flags determine qualitative formatting. 根据标准,
ios_base::fixed
和ios_base::scientific
标志确定定性格式。 If neither is set, the output is equivalent to the %g
format specifier of printf
. 如果两者均未设置,则输出等效于
printf
的%g
格式说明符。
According to man printf
, 根据
man printf
说法,
Trailing zeros are removed from the fractional part of the result;
尾随零从结果的分数部分中删除; a decimal point appears only if it is followed by at least one digit.
只有在小数点后跟至少一位数字时,小数点才会出现。
To get a .0
at the end despite the above rule, you would have to do something like print to a temporary string, search it for a decimal point, and retry in fixed
mode if not found. 尽管有上述规则,要在最后获得
.0
,您将必须执行类似打印到临时字符串的操作,搜索它的小数点,如果找不到则以fixed
模式重试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.