浮点数和整数的计算,Ruby 30 天刷题修行篇第十三话

大家好,我是 A Fei,大天要来解甚麽题目呢?让我们看下去:
(题目来源:Codewars


A child is playing with a ball on the nth floor of a tall building. The height of this floor, h, is known.

He drops the ball out of the window. The ball bounces (for example), to two-thirds of its height (a bounce of 0.66).

His mother looks out of a window 1.5 meters from the ground.

How many times will the mother see the ball pass in front of her window (including when it's falling and bouncing?

Three conditions must be met for a valid experiment:
Float parameter "h" in meters must be greater than 0
Float parameter "bounce" must be greater than 0 and less than 1
Float parameter "window" must be less than h.
If all three conditions above are fulfilled, return a positive integer, otherwise return -1.

Note:
The ball can only be seen if the height of the rebounding ball is strictly greater than the window parameter.

Examples:

- h = 3, bounce = 0.66, window = 1.5, result is 3

- h = 3, bounce = 1, window = 1.5, result is -1 

(Condition 2) not fulfilled).

题目给了一个情境:一个小孩正 n 层楼玩球。该楼层的高度为 h,他把球扔出窗外,球反弹到其三分之二的高度(bounce 等於 0.66)。 他的母亲从离地 1.5 公尺的窗户往外看。请问,妈妈会看到球在窗外经过多少次(包括球掉落和弹跳的时候)。此外,题目给了三个条件:

  1. h(公尺)是浮点数且必须大於 0
  2. bounce 必须大於 0 且小於 1
  3. 窗户高度必须小於 h

如果以上三个条件都满足,则回传看到球的次数(整数),反之则回传 -1

我的答案:

def bouncingBall(h, bounce, window)
  return -1 if h <= 0 || (bounce <= 0 && bounce >= 1) || window >= h 
  i = 1
  while h * bounce > window
    h = (h * bounce)
    i += 2
  end 
  i
end

<<:  【面试】coding interview

>>:  App 里的广告运用的格式跟广告商,不同平台的收益差别

摊平摊平,愈摊愈平

这也是很多输家最爱用的手段之一,进场时说是「成长型」投资,被套牢了,改口说是「价值型」投资,你真的懂...

Node.js介绍

Vue.js是一个前端框架,前端是由HTML、CSS和JavaScript三大元素所组成,所以我们前...

Day 16 | 同步与非同步- Coroutines的Scope

Scope Scope 指得是Coroutines 可以作用的范围。 在Main thread上或I...

[Day13] 第十三章-完成登入API (产生jwt token给前端使用)

前言 前面我们完成了注册相关的api 今天我们接续完成登入吧!! 今天的目标除了是使用laravel...

成为工具人应有的工具包-21 RegScanner

RegScanner 今天来认识看名字应该是注册表扫描?的小工具.... RegScanner 是可...