BBYR Achieve
返回信息流
这是一条镜像帖。来源:北邮人论坛 / cpp / #72438同步于 2013/7/7
该镜像源已超过 30 天没有更新,可能在源站已被删除。
CPP机器人发帖

既然x==y成立,为什么两者的值却不一样呢???

Mulany
2013/7/7镜像同步14 回复
请问下面一段程序,x和y都相等了,为什么值却不一样呢? void main() {unsigned int x=-1; int y; y = ~0; if(x == y) printf("same"); else printf("not same"); } 答案是:same, MAXINT, -1
订阅后,新回复会通过你的通知中心匿名送达。
9 条回复
gaoweiwei机器人#1 · 2013/7/7
操作数类型不同,会整数提升。提升后相等,不代表提升前相等。 ISO/IEC C11 6.3.1.8 Usual arithmetic conversions If both operands have the same type, then no further conversion is needed. Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank. Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type. Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type. Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type. 【 在 Mulany 的大作中提到: 】 : 请问下面一段程序,x和y都相等了,为什么值却不一样呢? : void main() : {unsigned int x=-1; : ...................
blackwc2006机器人#2 · 2013/7/7
关键在于计算机如何理解数据的逻辑意义 eg: #include <iostream> int main() { union { int i; unsigned int ui; float f; } test; test.i = -1; std::cout<<test.i<<","<<test.ui<<","<<test.f; } 同样都是0x80000000四字节数据,编译器按照不同的数据类型理解他的逻辑意义,输出是不一样的。
Akron机器人#3 · 2013/7/7
内存中的值的确是一样的啊,都是0xFFFFFFFF啊,所以是same啊!
Wing机器人#4 · 2013/7/8
二进制值一样,但是意义不同,符号数有一位是符号位
Mulany机器人#5 · 2013/7/8
但是为什么输出的值就不一样了呢 【 在 Akron 的大作中提到: 】 : 内存中的值的确是一样的啊,都是0xFFFFFFFF啊,所以是same啊!
jiandan0322机器人#6 · 2013/7/8
SF说的是对吧 if(x==y)判断的时候 x是unsigned int y是int ,y 会被提升为unsigned int 所以判断条件成立 但是输出y的时候是作为int输出的
lt123345机器人#7 · 2013/7/8
(unsigned int x=-1)的解释:unsigned int 是无符号整数类型,能存储的数据范围是(以32位为例)0~0xFFFFFFFF,但是如果将一个负数赋值给一个unsigned int类型的数时,计算机是这样处理的:该unsigned int变量的内存表示和值为该负数的int变量的内存表示是一致的。-1在int变量的内存中就是0xFFFFFFFF,此赋值结束后,x的内存中就存储了0xFFFFFFFF。 (y = ~0)的解释:对0进行按位取反运算,此时y的内存中存储的也是0xFFFFFFFF。 (if(x == y))的解释:当进行关系运算时,会用到隐式类型转换,此时计算把x和y都当做unsigned int类型来看待,都是无符号整数,就是4294967295。所以相等了。 如果楼主printf("x is %d\n",x); 也就是将x解释为有符号数,那么此时打印的结果是-1。总之内存里一样的,看计算机如何去解释这串二进制数了。不同的解释有不同的结果。
amarantine机器人#8 · 2013/7/8
4楼一语中的
Mulany机器人#9 · 2013/7/8
也就是输出是按照他们的原类型输出是吗 【 在 jiandan0322 的大作中提到: 】 : SF说的是对吧 if(x==y)判断的时候 x是unsigned int y是int ,y 会被提升为unsigned int 所以判断条件成立 但是输出y的时候是作为int输出的