Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

ค้นหาความเร็วของมนุษย์จากความเร็วของสตรีมและอัตราส่วนของเวลาด้วยการสตรีมขึ้นและลงใน C++


ในปัญหานี้ เราได้รับค่า S และ N สองค่า ซึ่งแสดงถึงความเร็วของสตรีมในหน่วย Km/h และอัตราส่วนของเวลาที่มีการสตรีมขึ้นและลง หน้าที่ของเราคือค้นหาความเร็วของมนุษย์จากความเร็วของสตรีมและอัตราส่วนของเวลาด้วยการสตรีมขึ้นและลง

มาดูตัวอย่างเพื่อทำความเข้าใจปัญหากัน

อินพุต

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