codewars——Bouncing Balls

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 0Float parameter “bounce” must be greater than 0 and less than 1Float 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 stricty greater than the window parameter.

/*
一個孩子在一棟高樓的第N層玩球。這層樓的高度h是已知的。
他把球從窗口扔了出去。球反彈(例如)到其高度的三分之二(反彈0.66)。
他母親從離地1.5米的窗戶向外看。
媽媽會看到球在她窗前經過多少次(包括什麼時候落下和彈跳)?
有效實驗必須滿足三個條件:
以米爲單位的浮點參數“h”必須大於0
浮動參數“bounce”必須大於0且小於1
浮動參數“window”必須小於h。
如果滿足上述三個條件,則返回正整數,否則返回-1。
注:
只有籃板球的高度比窗口參數嚴格時,才能看到球。
*/

#include <iostream>
using namespace std;
class Bouncingball
{
public:
    static int bouncingBall(double h, double bounce, double window);
};
int Bouncingball::bouncingBall(double h, double bounce, double window)
{
    int count = 0;
    if (h <= 0 || bounce >= 1 || bounce <= 0 || window >= h)
    {
        return -1;
    }
    if (h >= window)
        count += 1;
    while (true)
    {
        h *= bounce;
        if (h > window)
            count += 2;
        else
            break;
    }
    return count;
}

int main()
{
    Bouncingball ball;
    cout << ball.bouncingBall(30, 0.66, 1.5);
    return 0;
}

總結

用了循環,一開始一直想用遞歸方法,陷入怪圈

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章