给定一个直径为D厘米的圆柱玻璃。玻璃杯中的初始水位等于距底部H厘米。你以每秒M毫升的速度喝水。但是如果你不喝玻璃杯里的水,水位会以每秒N厘米的速度增加。任务是找出清空玻璃杯所需的时间,或者找出是否可以清空玻璃杯。
例子:
Input: D = 1, H = 1, M = 1, N = 1
Output: 3.65979
Input: D = 1, H = 2, M = 3, N = 100
Output: -1
方法:这是一道几何题。众所周知,玻璃的面积是pie * r 2 ,其中r表示半径即(D / 2) 。因此,要找到每秒消耗水的速率,请将给定的体积(已知 1 毫升等于 1 立方厘米)除以面积。
如果该值小于将水倒入玻璃杯中的速度,如果没有喝醉,则答案为否,否则玻璃杯可能是空的。
要找到时间,除以h / (v / (pie * r 2 ) – e) ,这就是杯子变空的时间。
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
double pie = 3.1415926535897;
// Function to return the time when
// the glass will be empty
double findsolution(double d, double h,
double m, double n)
{
double k = (4 * m) / (pie * d * d);
// Check the condition when the
// glass will never be empty
if (n > k)
return -1;
// Find the time
double ans = (h / (k - n));
return ans;
}
// Driver code
int main()
{
double d = 1, h = 1, m = 1, n = 1;
cout << findsolution(d, h, m, n);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
static double pie = 3.1415926535897;
// Function to return the time when
// the glass will be empty
static double findsolution(double d, double h,
double m, double n)
{
double k = (4 * m) / (pie * d * d);
// Check the condition when the
// glass will never be empty
if (n > k)
return -1;
// Find the time
double ans = (h / (k - n));
return ans;
}
// Driver code
public static void main(String[] args)
{
double d = 1, h = 1, m = 1, n = 1;
System.out.printf("%.5f",findsolution(d, h, m, n));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python3 implementation of the approach
pie = 3.1415926535897
# Function to return the time when
# the glass will be empty
def findsolution(d, h, m, n):
k = (4 * m) / (pie * d * d)
# Check the condition when the
# glass will never be empty
if (n > k):
return -1
# Find the time
ans = (h / (k - n))
return round(ans, 5)
# Driver code
d = 1
h = 1
m = 1
n = 1
print(findsolution(d, h, m, n))
# This code is contributed by Mohit Kumar
C#
// C# implementation of the approach
using System;
class GFG
{
static double pie = 3.1415926535897;
// Function to return the time when
// the glass will be empty
static double findsolution(double d, double h,
double m, double n)
{
double k = (4 * m) / (pie * d * d);
// Check the condition when the
// glass will never be empty
if (n > k)
return -1;
// Find the time
double ans = (h / (k - n));
return ans;
}
// Driver code
public static void Main(String[] args)
{
double d = 1, h = 1, m = 1, n = 1;
Console.Write("{0:F5}",
findsolution(d, h, m, n));
}
}
// This code is contributed by 29AjayKumar
Javascript
输出:
3.65979
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。