码迷,mamicode.com
首页 > 编程语言 > 详细

java之浮点数(笔记)

时间:2015-03-21 19:49:49      阅读:163      评论:0      收藏:0      [点我收藏+]

标签:

  1.在计算机中,浮点数并不同等于小数。

public static void main(String[] args) {
        double b1 = 0.1;
        double b2 = 0.2;
        double result = b1 + b2;
        System.out.print(result);
    }

  结果:0.30000000000000004

  原因:计算机使用二进制来存储数据。

  PS. 用浮点数做条件判断时要注意。比如(while(f != 0.3)可以会一直循环)。

  

  2.浮点数中大数加小数

public static void main(String[] args) {
        float f1 = 30000000;
        float f2 = 1;
        float r = f1 + f2;
        if(r < f1)
            System.out.println("left smaller");
        else
            System.out.println("what?");
    }

  结果:what?

  原因:浮点数越大,两个相邻浮点数的间隙越大。

 

  3.浮点数转为其他类型

public static void main(String[] args) {
        System.out.println((int)Double.NaN);
        System.out.println((int)Double.POSITIVE_INFINITY);
        System.out.println((int)Double.NEGATIVE_INFINITY);
    }

  结果:0 

     2147483647
     -2147483648

     

  

java之浮点数(笔记)

标签:

原文地址:http://www.cnblogs.com/programmer-kaima/p/4356002.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!