首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

-6+5>零

2013-03-26 
-6+50#include iostreamusing namespace stdvoid main(){int a-6unsigned int b5if((a+b)0) cout

-6+5>0

#include <iostream>
using namespace std;
void main()
{
int a=-6;
unsigned int b=5;
if((a+b)>0) cout<<"yes"<<endl;
system("pause");
}


我记得不同类型转换的时候规则是按大的转换或者相同大小按左值转换的,为啥啊?
输出yes
[解决办法]
-6先转为unsigned类型的(向小类型转化),然后在相加,两数之和只比 unsigned int的最大值小一,所以输出yes
[解决办法]
a+b试,先执行类型转化(unsigned)a,这样a = 4294967290 ,然后执行a+b = 4294967295.
所以你的程序输出yes。 
[解决办法]
低到高
int ->  unsigned int
[解决办法]
C89

3.2.1.5 Usual arithmetic conversions

Many binary operators that expect operands of arithmetic type cause conversions and yield result types in a similar way. The purpose is to yield a common type, which is also the type of the result. This pattern is called the usual arithmetic conversions: First, if either operand has type long double, the other operand is converted to long double. Otherwise, if either operand has type double, the other operand is converted to double. Otherwise, if either operand has type float, the other operand is converted to float. Otherwise, the integral promotions are performed on both operands. Then the following rules are applied: If either operand has type unsigned long int, the other operand is converted to unsigned long int. Otherwise, if one operand has type long int and the other has type unsigned int, if a long int can represent all values of an unsigned int, the operand of type unsigned int is converted to long int ; if a long int cannot represent all the values of an unsigned int, both operands are converted to unsigned long int. Otherwise, if either operand has type long int, the other operand is converted to long int. Otherwise, if either operand has type unsigned int, the other operand is converted to unsigned int. Otherwise, both operands have type int.

The values of operands and of the results of expressions may be represented in greater precision and range than that required by the type; the types are not changed thereby.

[解决办法]
引用:
-6先转为unsigned类型的(向小类型转化),然后在相加,两数之和只比 unsigned int的最大值小一,所以输出yes



正解。
楼主需要自习理解一下,不同类型之间类型转换该怎么转换。理解了,这种情况目测就能知道原因了。
[解决办法]
http://www.cppblog.com/izualzhy/archive/2011/10/12/158169.html
一个不错的讲解。可以看看
[解决办法]
类型转换了。
unsigned int 向小类型转换。
[解决办法]
这个讲得很好。

热点排行