简体   繁体   English

为什么printf()输出-1表示大整数?

[英]Why does printf() output -1 for large integers?

I'm reading the second edition of K&R book and one of the exercises requires printing all maximum integer values defined in limits.h header. 我正在阅读第二版K&R书籍,其中一个练习需要打印limits.h标题中定义的所有最大整数值。 However, this... 但是,这......

printf("unsigned int: 0 to %d\n", UINT_MAX);

... outputs the following: ...输出以下内容:

unsigned int: 0 to -1

How come I get -1? 我怎么得到-1? Anyone could explain this behaviour? 有谁能解释这种行为?

I'm using Digital Mars C compiler on Vista. 我在Vista上使用Digital Mars C编译器。

This is because UINT_MAX resolves to -1 if treated as a signed integer. 这是因为如果将UINT_MAX视为有符号整数,则UINT_MAX将解析为-1。 The reason for this is, that integers are represented in two's-complement . 原因是,整数用二进制表示。 As a consequence, -1 and 4294967296 (ie UINT_MAX) have the same bit representation (0xFFFFFFFF, ie all bits set) and that's why you get a -1 here. 因此,-1和4294967296(即UINT_MAX)具有相同的位表示(0xFFFFFFFF,即所有位设置),这就是为什么在这里得到-1的原因。

Update: 更新:
If you use "%u" as the format string you will get the expected result. 如果您使用“%u”作为格式字符串,您将获得预期的结果。

In the printf, I believe %d is a signed decimal integer, try %u instead. 在printf中,我相信%d是带符号的十进制整数,请尝试%u。

The max value of an unsigned int has the most significant bit set (it is all 1s). unsigned int的最大值具有最高有效位集(全部为1)。 With a signed int, the most significant bit specifies negative numbers, so when you're printing an unsigned int as a signed int, printf thinks it is negative. 使用signed int,最重要的位指定负数,因此当您将unsigned int打印为signed int时,printf认为它是负数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM