Find the length of the vector.
Input. Four integers x1, y1,
x2, y2 – the coordinates of the beginning and end of the
vector, respectively. All input data do not exceed 10000 by absolute value.
Output. The length
of a given vector up to the sixth decimal place.
Sample input |
Sample output |
1 1 2
2 |
1.414214 |
geometry
Algorithm analysis
The
coordinates of the vector a are (x2 – x1, y2
– y1), its length is
|a| =
Find the length of vector using a
formula.
scanf("%lf %lf %lf %lf",&x_1,&y_1,&x_2,&y_2);
res
= sqrt((x_2 - x_1)*(x_2 - x_1) + (y_2 - y_1)*(y_2 - y_1));
printf("%.6lf\n",res);
#include <stdio.h>
#include <math.h>
class Point
{
public:
int x, y;
Point(int x, int y) : x(x), y(y) {}
Point(void)
{
scanf("%d
%d",&x,&y);
}
};
class Vector
{
public:
int dx, dy;
Vector(Point B, Point E)
{
dx = E.x - B.x;
dy = E.y - B.y;
}
double Len(void)
{
return
sqrt(1.0*dx*dx + dy*dy);
}
};
int main(void)
{
Point a, b;
Vector v(a,b);
printf("%.6lf\n",v.Len());
return 0;
}
Java realization
import java.util.*;
public class Main
{
public static void main(String []args)
{
Scanner con = new Scanner(System.in);
double x1 = con.nextDouble();
double y1 = con.nextDouble();
double x2 = con.nextDouble();
double y2 = con.nextDouble();
double res =
Math.sqrt((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1));
System.out.printf(Locale.US,"%.6f\n",res);
con.close();
}
}
Java realization – classes
import java.util.*;
class Point
{
double x, y;
Point(double x, double y)
{
this.x = x;
this.y = y;
}
}
class Vector
{
double dx, dy;
Vector(Point B, Point E)
{
dx = E.x - B.x;
dy = E.y - B.y;
}
double getLength()
{
return Math.sqrt(dx*dx + dy*dy);
}
}
public class Main
{
public static void main(String[] args)
{
Scanner con = new Scanner(System.in);
double x = con.nextDouble(), y = con.nextDouble();
Point a = new Point(x,y);
x = con.nextDouble(); y = con.nextDouble();
Point b = new Point(x,y);
Vector v = new Vector(a,b);
//
System.out.printf("%.6f\n",v.getLength());
System.out.println(v.getLength());
con.close();
}
}