Home  >  Q&A  >  body text

What's wrong with this Java question?

/*
 * 一球从100米高度自由落下,每次落地后反跳回原来高度的一半,再落下,
 *    求它在第10次落地时共经过多少米?第10次反弹多高?
 * 
 */
修改的地方都加粗了

public class Demo {
    public static void main(String[] args){
        //小球反弹后的高度
        double height = 100;
        //y用于记录小球下落的高度
        double y = 0;
        //小球经过的总路程
        **double sum = 0;**
        
        for(int  i =1;i<=10;i++){
            //记录小球落下的高度
            y = height ;
            //小球每次反弹后的高度
            height = (**1.0**/2)*height;
            //因为第10次反弹的高度是不用加的
            if(i<=9){
                //小球的总路程
                sum =y+height;        
            }
        }
        System.out.println("共经过"+sum+"米");
        System.out.println("第10次反弹的高度是:"+height+"米");
    }
}
天蓬老师天蓬老师2686 days ago596

reply all(3)I'll reply

  • 欧阳克

    欧阳克2017-06-12 09:27:18

    height = (1/2)*height ; should be height = (1.0/2)*height ;, otherwise its value is always 0.

    Because of the type conversion of numeric operations, the result of integer division is also an integer, so the result of 1/2 is 0, not 0.5.

    Also y is reset every time it loops. Change to:

    public class Demo {
        public static void main(String[] args){
            //小球的高度
            double height = 100;
            //小球经过的距离
            double y = 0;
            for(int i=1;i<=10;i++){
                //记录小球每次往下落的距离,球弹起和下落,所以 height * 2
                y = y + height*2;
    
                //反弹的高度
                height = (1.0/2)*height ;
            }
            // 第一次落地没有经历弹起过程,需减掉初始高度
            y = y - 100;
            System.out.println("共经过"+y+"米");
            System.out.println("第10次反弹的高度是:"+height+"米");
        }
    }
    

    reply
    0
  • 三叔

    三叔2017-06-12 09:27:18

    y = height The y value is reset every time it loops, where is the accumulation...

    JavaScript code algorithm diagram

    var height = 100
    var sum = height;
    for (var i = 2; i <= 10; i++) {
        sum += height;
        height /= 2
    }
    // sum == 299.609375,即总路程
    
    // 最后一次是第10次弹起再下落的总长,所以再除以2才是弹起的高度
    height /= 2;    // 0.09765625

    reply
    0
  • 迷茫

    迷茫2017-06-12 09:27:18

    So the code can be written like this
    public class Demo {

    public static void main(String[] args){
        //小球的高度
        double height = 100;
        //第一次小球经过的距离
        double y = height;
        //不算上第一次,到第10次还要经历9次
        for(int i=1;i<=9;i++){
        //反弹的高度每次都是前一次的一半
            height = (1/2)*height;
            //每一次弹跳往返都是高度的两倍
            y += height*2;  
        }
        System.out.println("共经过"+y+"米");
        System.out.println("第10次反弹的高度是:"+height+"米");
    }

    }

    reply
    0
  • Cancelreply