C中unsigned int的行为 [英] Behavior of unsigned int in C

查看:76
本文介绍了C中unsigned int的行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C中无符号整数的大小为0 to 65,535 or 0 to 4,294,967,295.

我在C语言中使用以下代码进行了测试:

I tested with the following codes in C:

unsigned int number = 0;
number -= 300;
printf("%d\n", number);

输出:-300

我记得,如果unsigned int变量的值低于0,它应该绕回,并且我期望输出类似于4294966996.但是,从控制台打印的输出是-300.

I remember that if the value of unsigned int variable goes below 0, it should wrap around and I was expecting the output to be something like 4294966996. However the output printed from the console is -300.

我在C ++中测试了类似的语句,它确实给了我4294966996.

I tested similar statements in C++, it does give me 4294966996.

我的问题是:尽管输出是unsigned int,为什么输出-300?

My question is: Why is the output -300 despite the fact that it is an unsigned int?

PS:我浏览了几篇标题相似的帖子,但它们没有解决相同的问题:

PS: I've looked through several posts with similar title, but they are not addressing the same issue:

C语言中有符号与无符号int

未签名整数差异的意外结果

推荐答案

因为printf("%d\n", number);会打印一个带符号的值,即使该参数是无符号的.使用printf("%u\n", number);可以正确打印无符号值.

Because printf("%d\n", number); will print a signed value, even if the parameter is unsigned. Use printf("%u\n", number); for an unsigned value to be correctly printed.

这篇关于C中unsigned int的行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆