Найти точку пересечения прямой и окружности - C#
Формулировка задачи:
Задана окружность с центром в точке O(0,0) и радиусом R0, и прямая y = ax+b. Определить, пересекаются ли прямая и окружность. Если пересекаются, найти точку пересечения.
Решение задачи: «Найти точку пересечения прямой и окружности»
textual
Листинг программы
- class Programm
- {
- /*Circle properties*/
- static double x0, y0, r;
- /*Line properties*/
- static double k, p;
- public static void Main()
- {
- /*Init circle*/
- init("x0 = ", out x0);
- init("y0 = ", out y0);
- init("r = ", out r);
- /*Init line*/
- init("k = ", out k);
- init("p = ", out p);
- double a = square(k) + 1;
- double b = 2 * (k * (p - y0) - x0);
- double c = square(b - y0) + square(x0) - square(r);
- double x1, x2;
- if (trySolutionSquareEquation(a, b, c, out x1, out x2))
- {
- Console.WriteLine("First point : [{0};{1}]", x1, y(x1));
- Console.WriteLine("Second point : [{0};{1}]", x2, y(x2));
- }
- else
- {
- Console.WriteLine("Equation not have solution");
- }
- Console.ReadLine();
- }
- /*Function of line*/
- private static double y(double x)
- {
- return k * x + p;
- }
- /*Get square of value*/
- private static double square(double value)
- {
- return Math.Pow(value, 2.0);
- }
- /*Solving equation*/
- private static bool trySolutionSquareEquation(double a, double b, double c, out double x1, out double x2)
- {
- x1 = double.NaN;
- x2 = double.NaN;
- double discriminant = b * b - 4 * a * c;
- if (discriminant < 0)
- {
- return false;
- }
- double k = -b / 2 * a;
- discriminant /= 2 * a;
- x1 = k - Math.Sqrt(discriminant);
- x2 = k + Math.Sqrt(discriminant);
- return true;
- }
- private static void init(string message, out double value)
- {
- Console.Write(message);
- value = readDoubleFromTerminale();
- }
- private static double readDoubleFromTerminale()
- {
- string doubleString;
- double doubleValue;
- do
- {
- doubleString = Console.ReadLine();
- }
- while (!Double.TryParse(doubleString, out doubleValue));
- return doubleValue;
- }
- }
ИИ поможет Вам:
- решить любую задачу по программированию
- объяснить код
- расставить комментарии в коде
- и т.д