C++ code to find how long person will alive between presses


Suppose we have four numbers d, L, v1 and v2. Two presses are initially at location 0 and L, they are moving towards each other with speed v1 and v2 each. The width of a person is d, he dies if the gap between two presses is less than d. We have to find how long the person will stay alive.

So, if the input is like d = 1; L = 9; v1 = 1; v2 = 2;, then the output will be 2.6667

Steps

To solve this, we will follow these steps −

e := (L - d)/(v1 + v2)
return e

Example

Let us see the following implementation to get better understanding −

#include <bits/stdc++.h>
using namespace std;
float solve(int d, int L, int v1, int v2){
   float e = (L - d) / (float)(v1 + v2);
   return e;
}
int main(){
   int d = 1;
   int L = 9;
   int v1 = 1;
   int v2 = 2;
   cout << solve(d, L, v1, v2) << endl;
}

Input

1, 9, 1, 2

Output

2.66667

Updated on: 30-Mar-2022

69 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements