使用c++和VS2008管理整数时的错误

Bug when managing whole numbers using C++ and VS2008?

本文关键字:错误 整数 管理 c++ VS2008 使用      更新时间:2023-10-16

我正在调试一个c++程序,我发现,由于某种原因,在我的visual studio 2008版本下,一些数字似乎不能正确存储。例如,数字-3254535440似乎被存储为1040431856。这些数字足够小,可以存储在一个很长的long中,所以应该没有问题。如果运行以下代码,将显示两条错误消息。我在两台不同的机器上试过。任何想法?谢谢!

if (-3254535440 == 1040431856)
    printf("ERRORn");
long long j = -3254535440;
if (j == 1040431856)
    printf("ERROR2n");

在Microsoft Visual Studio 2008 Version 9.0.30729.1 SP下测试

文字仍然是int s。你需要把它们变成一个更大的字体:

long long j = -3254535440LL;

这并不适合32位类型(似乎您的int是),但一旦表示为long long,它将保持其值

使用更高的警告级别编译,您将得到一个警告:

#include <stdio.h>
int main()
{
    long long j = -3254535440;
    printf("%lldn",j);
}

编译器:

c:>cl /nologo /W4 test.cpp
test.cpp
test.cpp(5) : warning C4146: unary minus operator applied to unsigned type, result still unsigned
c:>test
1040431856

如前所述,声明一个long long字面量:

#include <stdio.h>
int main()
{
    long long j = -3254535440LL;
    printf("%lldn",j);
}
结果:

c:>cl /nologo /W4 test.cpp
test.cpp
c:>test
-3254535440
相关文章: