几个面试题,请大家帮我解答一下
1,unsing int a=6;int b=-20; (a+b> 6)?puts( "> 6 "):puts( " <6 ");
会是什么结果,为什么?
[解决办法]
> 6
因为有符号跟无符号运算时.,..自动转为无符号..20+6> 6
[解决办法]
b is signed so it is promoted to unsigned when operating a+b. So b is a huge positive integer now.
so a+b> b is true.
[解决办法]
mdejtod(稻草人) might be true. Actually I don 't know how signed and unsigned convert to each other. Forget what I was saying.
[解决办法]
> 6
-20在内存翻译成正数算
[解决办法]
调试了一下:
unsigned int a=6;int b=-20; (a+b> 6)?puts( "> 6 "):puts( " <6 "); //输出 > 6
printf( "\n%d\n ",a+b); //输出 -14
奇怪啊!
[解决办法]
P6689()
you are right
因为有符号跟无符号运算时
自动转为无符号
a+b is a huge positive integer
put( "> 6 ");
[解决办法]
会是puts( "> 6 "),但a+b的值是一个很大的数,因为在2进制中,如果b变为无符号的话那它的第一位就是1,那它的值就至少是1^31
不信你可以用%u来显示一下数值
[解决办法]
这个应该是与编译器无关。使用dev-c++ 4.9.9.2 和vs2005 clr console 测试输出结果是:
a+b=4294967282 (10进制整数表示)。
原因:
int b=-20 ,表示成机器码是0xffffffec,此时左数第一位二进制数是1,1是符号位,表示负数。
当将b类型强制转化为unsigned int 时,cpu只是认为这个符号位不再是符号位了,而是数据位,而此时这个b作为无符号整数是0xffffffec,表示成10进制就是4294967276,因此
a+b=6+4294967276=4294967282.
再说明一件事:有人输出-14,这个数因因为函数转化引起的。使用printf( "%d ",a+b)输出-14,而使用cout < <(a+b)或者Console::WriteLine(a+b)输出是4294967282.
不知这样分析是否合理?
[解决办法]
> 6
有符号跟无符号运算时,自动转为无符号
[解决办法]
#include <iostream>
using namespace std;
#include <stdio.h>
int main(){
bool a=-5;
cout < <(bool)a < <endl;
getchar();
}
BOOL值是不是=0为负, 别的都是正的啊.