小米笔试题之unsigned int 与int的转换问题

本文详细解析了C++中不同数值类型的自动类型转换规则,通过具体实例展示了int与unsigned int相加时的实际行为,揭示了类型转换过程中的陷阱,并提供了正确理解和避免错误的方法。
http://www.cnblogs.com/silver1116/archive/2012/10/09/2717599.html随笔- 7 文章- 0 评论- 0

小小笔试题(二)

1.9月21日,小米,电子科大笔试题:

?
void fun()
{
unsigned int a = 2013;
int b = -2;
int c = 0;
while (a + b > 0)
{
a = a + b;
c++;
}
printf("%d", c);
}

  问:输出是什么?

此题略有陷进。

a+b相加会自动转换为unsigned int类型,以前一直以为int和unsigned int相加会转换为int!

因此当a=1时,a+b不是-1,因此死循环,木有输出。

2.相关知识

C++算数运算类型转换

Arithmetic conversion proceeds in the following order:

Operand TypeConversion
One operand has typeThe other operand is converted to long double.
One operand has double typeThe other operand is converted to double.
One operand has float typeThe other operand is converted to float.
One operand has unsigned long long int typeThe other operand is converted to unsigned long long int
One operand has long long type.The other operand is converted to long long.
One operand has unsigned long int typeThe other operand is converted to unsigned long int.
One operand has unsigned int type and the other operand has long inttype and the value of the unsigned int can be represented in a long intThe operand with unsigned int type is converted to long int.
One operand has unsigned int type and the other operand has long inttype and the value of the unsigned int cannot be represented in a long intBoth operands are converted to unsigned long int.
One operand has long int typeThe other operand is converted to long int.
One operand has unsigned int typeThe other operand is converted to unsigned int.
Both operands have int typeThe result is type int.

3. 参考

由int与unsigned int 相加看c++类型转换

 

转载之处:http://www.cnblogs.com/silver1116/archive/2012/10/09/2717599.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值