表示任何双精度值所需的最大字符长度是多少?

编程入门 行业动态 更新时间:2024-10-10 13:21:25
本文介绍了表示任何双精度值所需的最大字符长度是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

当我将无符号的 8 位 int 转换为字符串时,我知道结果将始终最多为 3 个字符(对于 255),对于有符号的 8 位 int,我们需要 4 个字符,例如-128".

When I convert an unsigned 8-bit int to string then I know the result will always be at most 3 chars (for 255) and for an signed 8-bit int we need 4 chars for e.g. "-128".

现在我真正想知道的是浮点值也是一样的.将任何double"或float"值表示为字符串所需的最大字符数是多少?

Now what I'm actually wondering is the same thing for floating-point values. What is the maximum number of chars required to represent any "double" or "float" value as a string?

假设常规 C/C++ 双精度 (IEEE 754) 和常规十进制扩展(即没有 %e printf 格式).

Assume a regular C/C++ double (IEEE 754) and normal decimal expansion (i.e. no %e printf-formatting).

我什至不确定真正小的数字(即 0.234234)是否会比真正的大数字(表示整数的双精度数)更长?

I'm not even sure if the really small number (i.e. 0.234234) will be longer than the really huge numbers (doubles representing integers)?

推荐答案

标准头文件 在 C 中,或 在 C++, 包含几个与浮点类型的范围和其他指标有关的常量.其中之一是 DBL_MAX_10_EXP,表示所有 double 值所需的最大 10 次幂指数.由于 1eN 需要 N+1 个数字来表示,而且可能还有负号,那么答案是

The standard header <float.h> in C, or <cfloat> in C++, contains several constants to do with the range and other metrics of the floating point types. One of these is DBL_MAX_10_EXP, the largest power-of-10 exponent needed to represent all double values. Since 1eN needs N+1 digits to represent, and there might be a negative sign as well, then the answer is

int max_digits = DBL_MAX_10_EXP + 2;

这假设指数大于表示最大可能尾数值所需的位数;否则,也会有一个小数点后跟更多的数字.

This assumes that the exponent is larger than the number of digits needed to represent the largest possible mantissa value; otherwise, there will also be a decimal point followed by more digits.

更正

最长的数实际上是最小的可表示的负数:它需要足够的位数来覆盖指数和尾数.该值为 -pow(2, DBL_MIN_EXP - DBL_MANT_DIG),其中 DBL_MIN_EXP 为负数.很容易看出(并通过归纳证明)-pow(2,-N) 需要 3+N 个字符来表示非科学十进制表示(-0.",后跟 N 个数字).所以答案是

The longest number is actually the smallest representable negative number: it needs enough digits to cover both the exponent and the mantissa. This value is -pow(2, DBL_MIN_EXP - DBL_MANT_DIG), where DBL_MIN_EXP is negative. It's fairly easy to see (and prove by induction) that -pow(2,-N) needs 3+N characters for a non-scientific decimal representation ("-0.", followed by N digits). So the answer is

int max_digits = 3 + DBL_MANT_DIG - DBL_MIN_EXP

对于 64 位 IEEE double,我们有

For a 64-bit IEEE double, we have

DBL_MANT_DIG = 53 DBL_MIN_EXP = -1023 max_digits = 3 + 53 - (-1023) = 1079

更多推荐

表示任何双精度值所需的最大字符长度是多少?

本文发布于:2023-11-06 08:42:04,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1563209.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:所需   精度   长度   字符

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!