在 C++ 中根據水流速度和上游與下游時間之比求人的速度
在這個問題中,我們給定兩個值 S 和 N,分別表示水流速度(單位:公里/小時)和上游與下游時間之比。我們的任務是根據水流速度和上游與下游時間之比求人的速度。
讓我們舉個例子來理解這個問題,
輸入
S = 5, N = 2
輸出
15
解決方案
解決這個問題的一個簡單方法是使用划船問題的數學公式。那麼,讓我們看看這個公式是如何工作的:
speed of man = x km/h speed of stream = S km/h speed of man downstream i.e. with stream = (x+S) km/h speed of man upstream i.e. against stream = (x-S) km/h Time to travel the distance downstream = T Time to travel the distance upstream = n*T Distance travelled upstream = (x - S)*n*T Distance travelled upstream = (x + S)*T As both the distances are same, (x + S) * T = (x - S)*n*T x + S = nx - nS s + nS = nx - x s*(n + 1) = x(n - 1)
$$x=\frac{S*(S+1)}{(S-1)}$$
程式演示了我們解決方案的工作原理,
示例
#include <iostream>
using namespace std;
float calcManSpeed(float S, int n) {
return ( S * (n + 1) / (n - 1) );
}
int main() {
float S = 12;
int n = 3;
cout<<"The speed of man is "<<calcManSpeed(S, n)<<" km/hr";
return 0;
}輸出
The speed of man is 24 km/hr
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP