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

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 郑世光 中级黑马   /  2012-9-8 13:21  /  1261 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

解释下程序的输出结果:2.0...2.37

class XiaoShu
{
        public static void main(String[] args)
        {
                float f=2.365f;
                float b=Math.round(f*100)/100;
                float d=(float)Math.round(f*100)/100;   //1,加了float为什么就是2.37了?  2,这里的float转换的是Math.round(f*100)还是Math.round(f*100)/100
                System.out.println(b+"..."+d);
        }
}

3 个回复

倒序浏览
沙发。。。
回复 使用道具 举报
"1,加了float为什么就是2.37了?"

因为Math.round(f*100)返回的一个int型数据.
而(float)Math.round(f*100)是将int型强转为float型数据
(float)Math.round(f*100)/100是将float型数据除以一个int型数据,float的精度大于int的精度,最终结果当然是返回较大的那个类型的数据,即float型数据.



"2,这里的float转换的是Math.round(f*100)还是Math.round(f*100)/100"

强转的优先级大于算术运算的优先级,所以这里转换的是Math.round(f*100)哦.
回复 使用道具 举报
float d=(float)Math.round(f*100)/100;
首先Math.round()是将值舍入至最接近的整数或是指定的小数位数数字
所以Math.round(f*100)就是237.0
(float)Math.round(f*100)/100;
强制转换将int类型转换为float所以就是2.37
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马