Geometry creates various algorithm problems in several fields of computer science. Particularly in coding tests, geometric problems are frequently presented, often dealing with points, lines, polygons, and so on.
Problem: Calculate the Distance Between Two Points
Given two points A(x1, y1)
and B(x2, y2)
above, please write a program to calculate the Euclidean distance between these two points.
Problem Summary
- Input: The coordinates of the two points
(x1, y1)
and(x2, y2)
- Output: The distance between the two points
Distance Formula
The Euclidean distance can be calculated using the following formula:
distance = √((x2 - x1)² + (y2 - y1)²)
C# Code
Below is an example of C# code to solve the problem:
using System;
class Program
{
static void Main()
{
// Input coordinates for point A
Console.Write("Please enter the x coordinate of point A: ");
double x1 = Convert.ToDouble(Console.ReadLine());
Console.Write("Please enter the y coordinate of point A: ");
double y1 = Convert.ToDouble(Console.ReadLine());
// Input coordinates for point B
Console.Write("Please enter the x coordinate of point B: ");
double x2 = Convert.ToDouble(Console.ReadLine());
Console.Write("Please enter the y coordinate of point B: ");
double y2 = Convert.ToDouble(Console.ReadLine());
// Calculate distance
double distance = Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2));
// Output result
Console.WriteLine($"The distance between the two points A({x1}, {y1}) and B({x2}, {y2}) is {distance}.");
}
}
Code Explanation
In the above code, we ask the user to input the coordinates of points A and B, and then calculate the Euclidean distance. Here, we use the Math.Sqrt
and Math.Pow
methods to compute the square and the square root.
Test Cases
We consider several test cases to ensure that the program works correctly:
- Point A(0, 0) and Point B(3, 4): Result is 5
- Point A(1, 1) and Point B(1, 1): Result is 0
- Point A(2, 3) and Point B(5, 7): Result is approximately 5
Conclusion
Geometric problems are a highly useful topic in coding tests. Especially if you thoroughly understand and implement basic problems like distance calculation between points, it will greatly help you in solving more complex geometric problems. I hope you improve your algorithm problem-solving skills through consistent practice.