当前位置:网站首页>Kotlin算法入门求自由落体
Kotlin算法入门求自由落体
2022-08-11 08:01:00 【易庞宙】
/* 一球从100米高度自由落下,每次落地后反跳回原高度的一半;再落下, 求它在第10次落地时,共经过多少米?第10次反弹多高 这里用BigDecimal避免精度丢失 */ class FreeFallingBody { fun tradition() { //传统算法 循环10次计算这里用BigDecimal避免精度丢失 val distance = BigDecimal(100.0) var height = BigDecimal(100.0) var result: BigDecimal? = null val percentage = BigDecimal(2.0) for (i in 0..9) { height = height.divide(percentage) if (result == null) result = distance.add(height) else result = result.add(height) //System.out.println("distance" + result); } println(result) } /** * 这里用BigDecimal避免精度丢失 * 以1为次数起点正向递归求第n次后自由落体后小球运动了多少距离 * 自定义求第n次后自由落体后小球运动了多少距离 * 以及逆向求第k次前的第n次之间自由落体后小球运动了多少距离 * 递归逆向求运动距离时候distance第一次运动距离为 0 */ fun diyFreeFallingBody(fallingTimes: Int, thisTimes: Int, height: BigDecimal, percentageHeight: BigDecimal, distance: BigDecimal): BigDecimal { var distance = distance /**所求落体次数相同则直接返回高度 */ if (thisTimes == fallingTimes) return distance.add(height.divide(percentageHeight)) else if (thisTimes < fallingTimes) { /**反复正向递归求下一次自由落体高度 */ if (thisTimes == 1) distance = height val nextHeight = height.divide(percentageHeight) return diyFreeFallingBody(fallingTimes, thisTimes + 1, nextHeight, percentageHeight, distance.add(nextHeight)) } else if (thisTimes > fallingTimes + 1) { /**反复逆向递归求下一次自由落体高度 */ val lastHeight = height.multiply(percentageHeight) if (distance.toInt() == 0) distance = height println("distance$distance") return diyFreeFallingBody(fallingTimes, thisTimes - 1, lastHeight, percentageHeight, distance.add(lastHeight)) } else if (thisTimes == fallingTimes + 1) { return distanKotlince.add(height.multiply(percentageHeight)) } return BigDecimal(0) } }
边栏推荐
猜你喜欢
随机推荐
Conditional statements in TF; where()
用 Antlr 重构脚本解释器
1046 punches (15 points)
1051 复数乘法 (15 分)
1036 Programming with Obama (15 points)
One-hot in TF
软件测试常用工具的用途及优缺点比较(详细)
2022-08-10 mysql/stonedb-slow SQL-Q16-time-consuming tracking
【LeetCode】链表题解汇总
流式结构化数据计算语言的进化与新选择
支持各种文件快速重命名最简单的小技巧
FPGA 20个例程篇:11.USB2.0接收并回复CRC16位校验
klayout--导出版图为gds文件
IQUNIX A80 exploring TTC金粉 初体验
[C语言] sscanf如何实现sscanf_s?
Do you know the basic process and use case design method of interface testing?
Distributed Lock-Redission - Cache Consistency Solution
redis operation
Break pad source code compilation--refer to the summary of the big blogger
场地预订系统,帮助场馆提高坪效