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 Type | Conversion |
---|---|
One operand has type | The other operand is converted to long double. |
One operand has double type | The other operand is converted to double. |
One operand has float type | The other operand is converted to float. |
One operand has unsigned long long int type | The 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 type | The 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 int | The 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 int | Both operands are converted to unsigned long int. |
One operand has long int type | The other operand is converted to long int. |
One operand has unsigned int type | The other operand is converted to unsigned int. |
Both operands have int type | The result is type int. |
3. 参考