要求:
??????? 一个孩子正在一座高楼的 n 层玩球。该楼层的高度h是已知的。他把球扔出窗外。球反弹(例如)到其高度的三分之二(反弹 0.66)。他的母亲从离地面 1.5 米的窗户向外望去。妈妈会看到球在她的窗前经过多少次(包括它掉落和弹跳的时候)?
解法一:
#include <iostream>
#include <cmath>
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 n{ 1 };
int i{ 2 };
if (h < 0 || bounce < 0 || bounce >= 1 || window >= h || window < 0)
return -1;
double hight = h * bounce;
while (hight >window) {
n += 2;
hight = h * pow(bounce, i);
i += 1;
}
return n;
}
优秀解法:
#include <cmath>
using namespace std;
class Bouncingball
{
public:
static int bouncingBall(double h, double bounce, double window)
{
return (h<=0 || 0>=bounce || bounce>=1 || window>=h) ?
-1 : (int)(log(window/h)/log(bounce))*2+1;
}
};
注意:平视不等于经过
|