奇怪的“unsigned long long int”行为
#include <cstdio>
int main ()
{
unsigned long long int n;
scanf("%llu",&n);
printf("n: %llu\n",n);
n /= 3;
printf("n/3: %llu\n",n);
return 0;
}
无论我输入什么,我都会得到非常奇怪的输出,例如:
n: 1
n/3: 2863311531
or
n: 2
n/3: 2863311531
or
n: 1000
n/3: 2863311864
原因是什么?我应该如何正确地做到这一点?
(g++ 3.4.2,Win XP)
Possible Duplicate:
How do you printf an unsigned long long int?
#include <cstdio>
int main ()
{
unsigned long long int n;
scanf("%llu",&n);
printf("n: %llu\n",n);
n /= 3;
printf("n/3: %llu\n",n);
return 0;
}
Whatever I put in input, I get very strange output, for example:
n: 1
n/3: 2863311531
or
n: 2
n/3: 2863311531
or
n: 1000
n/3: 2863311864
What's the reason? How should I do this correctly?
(g++ 3.4.2, Win XP)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
问题在于 MinGW 依赖于
msvcrt.dll
运行时。尽管 GCC 编译器支持像long long
这样的 C99-ism,但处理格式字符串的运行时并不理解"%llu"
格式说明符。您需要使用 Microsoft 的 64 位整数格式说明符。我认为
"%I64u"
可以解决问题。如果您
#include
,您可以使用它提供的宏来提高可移植性:请注意,MSVC 在 VS 之前没有
inttypes.h
2010,所以如果你想移植到这些编译器,你需要挖掘你自己的inttypes.h
副本,或者从 VS 2010 中获取一个(我认为它可以与早期版本一起使用) MSVC 编译器,但我不完全确定)。话又说回来,为了移植到这些编译器,您需要对unsigned long long
声明执行类似的操作,这需要挖掘stdint.h
并使用 < code>uint64_t 而不是unsigned long long
。The problem is that MinGW relies on the
msvcrt.dll
runtime. Even though the GCC compiler supports C99-isms likelong long
the runtime which is processing the format string doesn't understand the"%llu"
format specifier.You'll need to use Microsoft's format specifier for 64-bit ints. I think that
"%I64u"
will do the trick.If you
#include <inttypes.h>
you can use the macros it provides to be a little more portable:Note that MSVC doesn't have
inttypes.h
until VS 2010, so if you want to be portable to those compilers you'll need to dig up your own copy ofinttypes.h
or take the one from VS 2010 (which I think will work with earlier MSVC compilers, but I'm not entirely sure). Then again, to be portable to those compilers, you'd need to do something similar for theunsigned long long
declaration, which would entail digging upstdint.h
and usinguint64_t
instead ofunsigned long long
.