奇怪的"无符号得到long long int"行为 [英] Strange "unsigned long long int" behaviour
问题描述
可能重复:结果
怎样的printf一个unsigned long长整型?
块引用>的#include< cstdio>诠释的main()
{
无符号长长整型N;
scanf函数(%LLU,&安培; N);
的printf(N:%LLU \\ N,N);
N / = 3;
的printf(N / 3%LLU \\ N,N);
返回0;
}无论我把投入,我得到很奇怪的输出,例如:
N:1
N / 3:2863311531或
N:2
N / 3:2863311531或
N:1000
N / 3:2863311864什么原因?我应该怎么做是否正确?
(G ++ 3.4.2,WIN XP)
解决方案的问题是,MinGW的依赖于
MSVCRT.DLL
运行。即使GCC编译器支持C99-主义像长长
这是处理格式字符串不理解%LLU<运行/ code>格式说明。
您需要使用微软的格式指定为64位整数。我认为,
%I64u
会做的伎俩。如果您
的#include&LT; inttypes.h&GT;
你可以使用它提供的是多一点的便携式宏:INT的main()
{
无符号长长整型N;
scanf函数(%SCNu64,&安培; N);
的printf(N:%PRIu64\\ N,N);
N / = 3;
的printf(N / 3%PRIu64\\ N,N);
返回0;
}需要注意的是MSVC不具有
inttypes.h
到2010年VS,所以如果你想移植到这些编译器,你需要挖掘你自己的副本inttypes.h
或采取从2010年的VS之一(我认为将与早期MSVC编译器的工作,但我不能完全确定)。话又说回来,可以移植到这些编译器,你需要做的无符号长长
声明,这将需要挖stdint类似的东西.H
,并使用uint64_t中
而不是无符号长长
。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)
解决方案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:int main () { unsigned long long int n; scanf("%"SCNu64, &n); printf("n: %"PRIu64"\n",n); n /= 3; printf("n/3: %"PRIu64"\n",n); return 0; }
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
.这篇关于奇怪的&QUOT;无符号得到long long int&QUOT;行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!