* * A ball from the height of 100 meters free to fall, every time after landing back to the original height of half, and then fell, begging it in the 10th time when the ground, a total of how many meters. 10th time rebound How high here with BigDecimal to avoid the loss of precision * *classFreefallingbody {FunTradition () {//traditional algorithm loop 10 times compute here with BigDecimal to avoid precision lossValDistance = BigDecimal (100.0)varHeight = BigDecimal (100.0)varResult:bigdecimal? =NULLValPercentage = BigDecimal (2.0) for(I in0..9) {height = height.divide (percentage)if(Result = =NULL) result = Distance.add (height)Else result = Result.add (height)//system.out.println ("distance" + result); println (Result)}/** * Here use BigDecimal to avoid the loss of precision * with 1 as the number of times the beginning of the first forward recursion after the free fall after the small ball movement how many distance * custom to ask the nth time since How much distance from the small ball movement after the fall and the inverse of the nth time before the first n before the free fall of the small ball movement how many distances * recursive reverse to seek the movement distance distance the first time to move distance of 0 * * *FunDiyfreefallingbody (Fallingtimes:int, Thistimes:int, Height:bigdecimal, percentageheight:bigdecimal, Distance: BigDecimal): BigDecimal {varDistance = distance/** the same as the number of falling objects directly return to Height * *if(Thistimes = = fallingtimes) returnDistance.add (Height.divide (percentageheight))else if(Thistimes < Fallingtimes) {/** repeated forward recursion for the next free fall Height * *if(Thistimes = 1) distance = heightValNextheight = Height.divide (percentageheight) returnDiyfreefallingbody (Fallingtimes, Thistimes + 1, nextheight, Percentageheight, Distance.add (nextHeight))}else if(Thistimes > fallingtimes + 1) {/** repeated reverse recursion to find the next free fall Height * *ValLastheight = height.multiply (percentageheight)if(Distance.toint () = = 0) distance = height println ("Distance$Distance") returnDiyfreefallingbody (Fallingtimes, ThisTimes-1, Lastheight, Percentageheight, Distance.add (lastheight) )
}else if(Thistimes = = fallingtimes + 1) { returnDistankotlince.add (Height.multiply (percentageheight))} returnBigDecimal (0)}}