给定一个高度合适的圆柱体 , & 半径 。任务是找到可以插入其中的最长杆的长度。
例子:
Input : h = 4, r = 1.5
Output : 5
Input : h= 12, r = 2.5
Output : 13
方法:
从图中可以清楚地看出,我们可以使用毕达哥拉斯定理,将圆柱体的高度设为垂直,将圆柱体的直径设为底,将棒的长度设为斜边,从而得出棒的长度。
因此, l 2 = h 2 + 4 * r 2 。
所以,
l = √(h2 + 4*r2)
下面是上述方法的实现:
C++
// C++ Program to find the longest rod
// that can be fit within a right circular cylinder
#include
using namespace std;
// Function to find the side of the cube
float rod(float h, float r)
{
// height and radius cannot be negative
if (h < 0 && r < 0)
return -1;
// length of rod
float l = sqrt(pow(h, 2) + 4 * pow(r, 2));
return l;
}
// Driver code
int main()
{
float h = 4, r = 1.5;
cout << rod(h, r) << endl;
return 0;
}
Java
// Java Program to find the longest rod
// that can be fit within a right circular cylinder
import java.io.*;
class GFG {
// Function to find the side of the cube
static float rod(float h, float r)
{
// height and radius cannot be negative
if (h < 0 && r < 0)
return -1;
// length of rod
float l = (float)(Math.sqrt(Math.pow(h, 2) + 4 * Math.pow(r, 2)));
return l;
}
// Driver code
public static void main (String[] args) {
float h = 4;
float r = 1.5f;
System.out.print(rod(h, r));
}
}
// This code is contributed by anuj_67..
Python 3
# Python 3 Program to find the longest
# rod that can be fit within a right
# circular cylinder
import math
# Function to find the side of the cube
def rod(h, r):
# height and radius cannot
# be negative
if (h < 0 and r < 0):
return -1
# length of rod
l = (math.sqrt(math.pow(h, 2) +
4 * math.pow(r, 2)))
return float(l)
# Driver code
h , r = 4, 1.5
print(rod(h, r))
# This code is contributed
# by PrinciRaj1992
C#
// C# Program to find the longest
// rod that can be fit within a
// right circular cylinder
using System;
class GFG
{
// Function to find the side
// of the cube
static float rod(float h, float r)
{
// height and radius cannot
// be negative
if (h < 0 && r < 0)
return -1;
// length of rod
float l = (float)(Math.Sqrt(Math.Pow(h, 2) +
4 * Math.Pow(r, 2)));
return l;
}
// Driver code
public static void Main ()
{
float h = 4;
float r = 1.5f;
Console.WriteLine(rod(h, r));
}
}
// This code is contributed by shs
PHP
Javascript
输出:
5