当前位置: 动力学知识库 > 问答 > 编程问答 >

c - Why unsigned int contained negative number

问题描述:

What I know about unsigned numerics (unsigned short, int and longs), that It contains positive numbers only, but the following simple program successfully assigned a negative number to an unsigned int:

 1 /*

2 * =====================================================================================

3 *

4 * Filename: prog4.c

5 *

6 * =====================================================================================

7 */

8

9 #include <stdio.h>

10

11 int main(void){

12

13 int v1 =0, v2=0;

14 unsigned int sum;

15

16 v1 = 10;

17 v2 = 20;

18

19 sum = v1 - v2;

20

21 printf("The subtraction of %i from %i is %i \n" , v1, v2, sum);

22

23 return 0;

24 }

The output is :

The subtraction of 10 from 20 is -10

网友答案:

%i is the format specifier for a signed integer; you need to use %u to print an unsigned integer.

网友答案:

With printf, the %i format outputs a signed int. Use %u to output an unsigned int. This is a common issue when beginning C programming. To address your question, the result of v1 - v2 is -10, but sum is an unsigned int, so the real answer is probably something like 4294967286 (232 - 10). See what you get when you use The subtraction of %i from %i is %u \n. :)

网友答案:

Signed int and unsigned int are the same size in memory, the only difference between them is how you intepret them. Signed values use a twos complement representation.

If you put 0xFFFFFFFF in a 4 byte memory location, and then ask what is the value in there? Well if we interpret it as a signed int, then it is -1, but if we interpret it as an unsigned int then the value is 4294967295. Either way it's the same bit pattern, the difference is what meaning you give it.

When you assigned 10 - 20 into an unsigned int, you calculated a value of -10 (C doesn't do overflow or underflow checking), that's a bit pattern of 0xFFFFFFF6, which means -10 in a signed int or 4294967286 in an unsigned int. If you then tell the compiler (by using %i) to print a signed int then it interprets that bit pattern as a signed int and prints -10, if you told the compiler (by using %u) to print an unsigned int then it interprets that bit pattern as unsigned and prints 4294967286.

网友答案:

Because unsigned int value that is stored in sum is treated like signed decimal integer in printf %i

分享给朋友:
您可能感兴趣的文章:
随机阅读: