📜  检查一条线是否通过原点

📅  最后修改于: 2021-10-23 08:32:26             🧑  作者: Mango

给定直线的两个坐标为 (x1, y1) 和 (x2, y2),求通过这些点的直线是否也通过原点。

例子:

Input : (x1, y1) = (10, 0)
        (x2, y2) = (20, 0)
Output : Yes
The line passing through these points
clearly passes through the origin as 
the line is x axis.

Input : (x1, y1) = (1, 28)
        (x2, y2) = (2, 56)
Output : Yes

方法:通过两点 (x1, y1) 和 (x2, y2) 的直线方程为
y-y1 = ((y2-y1) / (x2-x1))(x-x1) + c
如果直线也通过原点,则c=0,所以直线方程变为
y-y1 = ((y2-y1) / (x2-x1))(x-x1)
在上面的等式中保持 x=0, y=0 我们得到,
x1(y2-y1) = y1(x2-x1)
因此,如果通过两个坐标 (x1, y1) 和 (x2, y2) 的任何线也通过原点 (0, 0),则必须满足上述等式。

C++
/* C++ program to find if line passing through
   two coordinates also passes through origin
   or not */
#include 
using namespace std;
 
bool checkOrigin(int x1, int y1, int x2, int y2)
{
   return (x1 * (y2 - y1) == y1 * (x2 - x1));
}
 
// Driver code
int main()
{
    if (checkOrigin(1, 28, 2, 56) == true)
      cout << "Yes";
    else
      cout << "No";
    return 0;
}


Java
// Java program to find if line passing through
// two coordinates also passes through origin
// or not
import java.io.*;
 
class GFG {
     
    static boolean checkOrigin(int x1, int y1,
                                       int x2, int y2)
    {
        return (x1 * (y2 - y1) == y1 * (x2 - x1));
    }
 
    // Driver code
    public static void main (String[] args)
    {
        if (checkOrigin(1, 28, 2, 56) == true)
            System.out.println("Yes");
        else
            System.out.println("No");
    }
}
 
// This code is contributed by Ajit.


Python3
# Python program to find if line
# passing through two coordinates
# also passes through origin or not
 
def checkOrigin(x1, y1, x2, y2):
    return (x1 * (y2 - y1) == y1 * (x2 - x1))
     
# Driver code
if (checkOrigin(1, 28, 2, 56) == True):
    print("Yes")
else:
    print("No")
     
# This code is contributed
# by Anant Agarwal.


C#
// C# program to find if line passing through
// two coordinates also passes through origin
// or not
using System;
 
class GFG {
 
    static bool checkOrigin(int x1, int y1,
                            int x2, int y2)
    {
        return (x1 * (y2 - y1) == y1 * (x2 - x1));
    }
 
    // Driver code
    public static void Main()
    {
        if (checkOrigin(1, 28, 2, 56) == true)
            Console.WriteLine("Yes");
        else
            Console.WriteLine("No");
    }
}
 
// This code is contributed by vt_m.


PHP


Javascript


输出:
Yes