A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© hdhunter 中级黑马   /  2015-11-25 14:24  /  802 人查看  /  5 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

short s1 = 1; s1 = s1 + 1;有什么错? short s1 = 1; s1 += 1;有什么错?

5 个回复

倒序浏览
第一个有错,第二个没错,
1默认为int型,s1+1是short+int,结果为int,再赋值给short就会出错所以第一个错
但是+=符号就不会错,就是这样
回复 使用道具 举报
type mismatch: cannot convert from int to short,因为s1=s1+1中的1是int类型的,需强制转换才行. s1 = (short) (s1 + 1);
回复 使用道具 举报
Little_jie 发表于 2015-11-25 14:32
type mismatch: cannot convert from int to short,因为s1=s1+1中的1是int类型的,需强制转换才行. s1 = (sh ...

好厉害。
回复 使用道具 举报

编译器上都有报错提示信息的,可以看下
回复 使用道具 举报
本帖最后由 梦想家Eva 于 2015-11-25 18:49 编辑

嗯,对的,
type mismatch: cannot convert from int to short,
因为s1=s1+1中的1是int类型的,s1+1后结果为int,需强制转换才行. s1 = (short) (s1 + 1);
而s +=1; +=是java中的赋值运算符,会将s+1的结果自动转换后,再赋值给s.
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马