题解 | #计算小球走过的路程和反弹高度#
计算小球走过的路程和反弹高度
https://www.nowcoder.com/practice/ac674f68367149d5ad1f857a379e69c9
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
// 下落的高度和落地的次数
double h;
int n;
cin >> h;
cin >> n;
double distance = h;
double height = distance/2;
// write your code here......
for (int i = 1; i < n; ++i)
{
distance += 2 * height;
height = height / 2;
}
cout << fixed <<setprecision(1) << distance <<" "<<setprecision(1)<< height << endl;
return 0;
}
稍微写一下待求的量我们可以找到规律。
1 | h | h/2 |
2 | h+2×h/2 | h/4 |
3 | h+2×h/2+2×h/4 | h/8 |
... | ... | ... |
初始化的为distance=h,distance=h/2。然后按规律循环求和就行了。
C++题解 文章被收录于专栏
记录在牛客网用C++刷题的题解思路