这里给出半径为r且垂直高度为h的右圆锥体,该圆锥体被刻在一个立方体中,而立方体又被刻在一个球体中,任务是找到球体的半径。
例子:
Input: h = 5, r = 6
Output: 1.57306
Input: h = 8, r = 11
Output: 2.64156
方法:
- 令立方体的边= a
- 令球体的半径= R
- 我们知道, a = h *r√2//(h +√2* r) (请参阅此处)
- 另外, R = a / 2 (请参阅此处)
- 因此, R =(h *r√2/ 2 /(h +√2* r))/ 2
下面是上述方法的实现:
C++
// C++ Program to find the biggest sphere
// which is inscribed within a cube which in turn
// inscribed within a right circular cone
#include
using namespace std;
// Function to find the radius of the sphere
float sphereSide(float h, float r)
{
// height and radius cannot be negative
if (h < 0 && r < 0)
return -1;
// radius of the sphere
float R = ((h * r * sqrt(2)) / (h + sqrt(2) * r)) / 2;
return R;
}
// Driver code
int main()
{
float h = 5, r = 6;
cout << sphereSide(h, r) << endl;
return 0;
}
Java
// Java Program to find the biggest sphere
// which is inscribed within a cube which in turn
// inscribed within a right circular cone
import java.lang.Math;
class GFG
{
// Function to find the radius of the sphere
static float sphereSide(float h, float r)
{
// height and radius cannot be negative
if (h < 0 && r < 0)
return -1;
// radius of the sphere
float R = (float)((h * r * Math.sqrt(2)) /
(h + Math.sqrt(2) * r)) / 2;
return R;
}
// Driver code
public static void main(String[] args)
{
float h = 5, r = 6;
System.out.println(sphereSide(h, r));
}
}
// This code is contributed by Code_Mech.
Python3
# Program to find the biggest sphere
# which is inscribed within a cube which in turn
# inscribed within a right circular cone
import math
# Function to find the radius of the sphere
def sphereSide(h, r):
# height and radius cannot be negative
if h < 0 and r < 0:
return -1
# radius of the sphere
R = (((h * r * math.sqrt(2))) /
(h + math.sqrt(2) * r) / 2)
return R
# Driver code
h = 5; r = 6
print(sphereSide(h, r))
# This code is contributed by Shrikant13
C#
// C# Program to find the biggest sphere
// which is inscribed within a cube which in turn
// inscribed within a right circular cone
using System;
class GFG
{
// Function to find the radius of the sphere
static float sphereSide(float h, float r)
{
// height and radius cannot be negative
if (h < 0 && r < 0)
return -1;
// radius of the sphere
float R = (float)((h * r * Math.Sqrt(2)) /
(h + Math.Sqrt(2) * r)) / 2;
return R;
}
// Driver code
public static void Main()
{
float h = 5, r = 6;
Console.WriteLine(sphereSide(h, r));
}
}
// This code is contributed by Code_Mech
PHP
Javascript
输出:
1.57306