题解 | #求小球落地5次后所经历的路程和第5次反弹的高度#
求小球落地5次后所经历的路程和第5次反弹的高度
https://www.nowcoder.com/practice/2f6f9339d151410583459847ecc98446
#include <iostream> using namespace std; class Height { private: //高度 double h; public: //构造函数 Height(const int h); //析构函数 ~Height(); //第n次弹起的高度 const double heightn(const int n)const; //第n次落地时经历的路程 const double journeyn(const int n)const; }; Height::Height(const int h) { this->h = h; return; } Height::~Height() { } const double Height::heightn(const int n) const { //由于每次弹起一半高度,只需将原本高度进行弹起次数次除以2 double h = this->h; for (int i = 0; i < n; i++) h /= 2; return h; } const double Height::journeyn(const int n) const { //第n次落地所经历的路程应当为原本高度加上1至(n-1)次弹起的高度以及下落的高度(默认落回原位,弹起和下落高度相等) double j = this->h; for (int i = 1; i < n; i++) j += 2 * this->heightn(i); return j; } int main() { int a; while (cin >> a) { // 注意 while 处理多个 case Height h(a); cout << h.journeyn(5) << endl; cout << h.heightn(5) << endl; } } // 64 位输出请用 printf("%lld")