给定一条直线在两个轴上的截距为m和n 。任务是从原点找到这条直线上法线的长度。
例子:
Input: m = 5, n = 3
Output: 2.57248
Input: m = 13, n = 9
Output: 7.39973
方法:线的法线是从垂直于给定线的点绘制的线段。
设p为从原点绘制到一条线的法线长度,该线与 x 轴的正方向对角θ ,如下所示。
然后,我们有cos Θ = p / m和sin Θ = p / n
因为, sin 2 Θ + cos 2 Θ = 1
所以, (p/m) 2 + (p/n) 2 = 1
我们得到, p = m * n / √(m 2 + n 2 )
下面是上述方法的实现:
C++
// C++ implementation of the approach
#include
using namespace std;
// Function to find the normal
// of the straight line
float normal(float m, float n)
{
// Length of the normal
float N = (fabsf(m) * fabsf(n))
/ sqrt((fabsf(m) * fabsf(m))
+ (fabsf(n) * fabsf(n)));
return N;
}
// Driver code
int main()
{
float m = -5, n = 3;
cout << normal(m, n);
return 0;
}
Java
// Java implementation of the approach
class GFG
{
// Function to find the normal
// of the straight line
static float normal(float m, float n)
{
// Length of the normal
float N = (float) ((Math.abs(m) * Math.abs(n))
/ Math.sqrt((Math.abs(m) * Math.abs(m))
+ (Math.abs(n) * Math.abs(n))));
return N;
}
// Driver code
public static void main(String[] args)
{
float m = -5, n = 3;
System.out.println(normal(m, n));
}
}
// This code has been contributed by 29AjayKumar
Python3
# Python3 implementation of the approach
import math;
# Function to find the normal
# of the straight line
def normal(m, n):
# Length of the normal
N = ((abs(m) * abs(n)) /
math.sqrt((abs(m) * abs(m)) +
(abs(n) * abs(n))));
return N;
# Driver code
m = -5; n = 3;
print(normal(m, n));
# This code is contributed
# by Akanksha Rai
C#
// C# implementation of the approach
using System;
class GFG
{
// Function to find the normal
// of the straight line
static float normal(float m, float n)
{
// Length of the normal
float N = (float)((Math.Abs(m) * Math.Abs(n)) /
Math.Sqrt((Math.Abs(m) * Math.Abs(m)) +
(Math.Abs(n) * Math.Abs(n))));
return N;
}
// Driver code
public static void Main()
{
float m = -5, n = 3;
Console.Write(normal(m, n));
}
}
// This code is contributed by Akanksha Rai
PHP
Javascript
输出:
2.57248
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。