[英]Difference in digits10 between GCC and MSVC
I have the following code:我有以下代码:
#include <iostream>
#include <limits>
int main()
{
std::cout << std::numeric_limits<unsigned long long>::digits10 << std::endl;
return 0;
}
Can someone please explain Why is there a difference between the two?有人可以解释为什么两者之间有区别吗? I would have expected such a constant would be the same regardless of the compiler.无论编译器如何,我都希望这样的常量是相同的。
If Visual C++ 2008 returns 18
for std::numeric_limits<unsigned long long>::digits10
, it is a bug (I don't have Visual C++ 2008 installed to verify the described behavior).如果 Visual C++ 2008 为std::numeric_limits<unsigned long long>::digits10
返回18
,则这是一个错误(我没有安装 Visual C++ 2008 来验证所描述的行为)。
In Visual C++ (at least for 32-bit and 64-bit Windows), unsigned long long
is a 64-bit unsigned integer type and is capable of representing all of the integers between zero and 18,446,744,073,709,551,615 (2 64 - 1).在 Visual C++ 中(至少对于 32 位和 64 位 Windows), unsigned long long
是 64 位无符号整数类型,能够表示 0 到 18,446,744,073,709,551,615 (2 64 - 1) 之间的所有整数。
Therefore, the correct value for digits10
here is 19 because an unsigned long long
can represent 9,999,999,999,999,999,999 (19 digits) but cannot represent 99,999,999,999,999,999,999 (20 digits).因此,这里digits10
的正确值是19,因为unsigned long long
可以表示9,999,999,999,999,999,999(19 位),但不能表示99,999,999,999,999,999,999(20 位)。 That is, it can represent every 19 digit number but not every 20 digit number.也就是说,它可以代表每 19 位数字,但不能代表每 20 位数字。
When compiled with Visual C++ 2010, your program prints the expected 19.使用 Visual C++ 2010 编译时,您的程序会打印预期的 19。
In general, the statement一般来说,声明
I would have expected such a constant would be the same regardless of the compiler.无论编译器如何,我都希望这样的常量是相同的。
is not correct because the size of a type in C isn't fixed.不正确,因为 C 中类型的大小不固定。 The standard only mandates a minimum limit and compilers are free to use wider types.该标准只规定了最低限度,编译器可以自由使用更广泛的类型。 For example some weird compilers on a 32 or 64-bit computer may have CHAR_BIT = 9
and unsigned long long
wouldn't be 64 bit any more, or it may use different 1's complement or some other number encodings.例如,32 位或 64 位计算机上的一些奇怪的编译器可能具有CHAR_BIT = 9
并且unsigned long long
不再是 64 位,或者它可能使用不同的 1 的补码或其他一些数字编码。 In short, the result may vary between compilers.简而言之,结果可能因编译器而异。
However in case that unsigned long long
is a 64-bit type then it's definitely a bug.但是,如果unsigned long long
是 64 位类型,那么它绝对是一个错误。 I've just checked and saw that the bug has been fixed in VS 2008. The correct value of 19 is returned刚刚查了一下,VS 2008 已经修复了这个bug,返回了正确的值19
numeric_limits::digits10 specifies the number of decimal digits to the left of the decimal point that can be represented without a loss of precision. numeric_limits::digits10指定可以在不损失精度的情况下表示的小数点左侧的小数位数。 So, I guess it will differ from compiler to compiler depending on their implementation detail.所以,我想它会因编译器而异,具体取决于它们的实现细节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.