黑马程序员技术交流社区

标题: 一道习题,求详解(选C的原因) [打印本页]

作者: HM张博文    时间: 2013-5-29 13:49
标题: 一道习题,求详解(选C的原因)
本帖最后由 HM张博文 于 2013-5-29 16:43 编辑

Analyze the following fragment:
double sum = 0;
double d = 0;
while (d != 10.0) {
  d += 0.1;
  sum += sum + d;
}

A. The program does not compile because sum and d are declared double, but assigned with integer value 0.
B. The program never stops because d is always 0.1 inside the loop.
C. The program may not stop because of the phenomenon referred to as numerical inaccuracy for operating with floating-point numbers.
D. After the loop, sum is 0 + 0.1 + 0.2 + 0.3 + ... + 1.9

The correct answer is C。
Can you tell me why?

作者: 黑马-许鹏    时间: 2013-5-29 14:29
      选项c的意思大概是说:该程序不会停止因为涉及到浮点数操作,会出现数值不准确现象。我在本机上验证了一下,果然不会停下来。
     因为double是双精度型的小数,精确度达到16位的,所以它不会和10.0相同。如果要计算0.1+0.2+……+9.9的话下列这段代码可完成。
  1.                 class Demo{
  2.             public static void main(String[] args){
  3.                     double sum = 0;
  4.                     double d = 0;
  5.                     while (d<10.0) {
  6.                       d += 0.1;
  7.                       sum += sum + d;
  8.                     }
  9.                     System.out.println(sum);
  10.            }
  11.                 }
复制代码

作者: 黑马陈涛    时间: 2013-5-29 15:13
    这应该涉及到浮点数在计算机中的存储问题吧,浮点数是以符号位+指数位+尾数部分组成,也就是在进行+0.1的操作的时候,由于0.1转换成二进制时不错的话应该是0.000110011……一个十分近似的值,所以在以这个近似值进行运算,会出现一定的误差也就是在计算时d的值不会是0.1  0.2 0.3 ……这样的值,而是在某一部分误差变大使得d不会再是小数点后只有一位,而是存在许多小数,这样d就不会再能够得到10.0的值而是9.99999……98和10.099999……98这两个10.0附近的值,从计算结果中我们可以看到在第三次运算时已经出现误差得到0.30000……004
    如果将d != 10.0,改成d!=0.2(或者0.4,0.5等几个值)程序是可以停止的
作者: 黑马陈涛    时间: 2013-5-29 15:36
给个可以运行的代码,有点麻烦
import java.text.*;
class Demo
{
        private static final double a = 4.0;
        public static void main(String[] args)
        {
               
                double d=0.0;
                double sum=0.0;
                while (Double.parseDouble(new java.text.DecimalFormat("0.0").format(d)) != a)
                        {
                        d += 0.1;
                        System.out.println(new java.text.DecimalFormat("0.0").format(d));
                        sum +=d;
                }
        }
}
作者: 殇_心。    时间: 2013-5-29 16:20
如果问题已解决,请及时修改分类,否则继续提问,谢谢合作!




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2