C/C++ Programming Learning-Week 3 ⑤ Calculate the distance between two points

Topic link

Title description

Input the coordinates of two points (X1, Y1), (X2, Y2), calculate and output the distance between the two points.

There
are multiple groups of input data, each group occupies a line, composed of 4 real numbers, which represent x1, y1, x2, y2, and the data are separated by spaces.

Output
For each group of input data, output one line, and the result retains two decimal places.

Sample Input

0 0 0 1
0 1 1 0

Sample Output

1.00
1.41

Ideas

Enter the coordinates of two points, calculate and output the distance between the two points.

Pay attention to three points:
①Use the square root to calculate the distance between two points, the square root function is sqrt()
②Use the square root function, you need to take the lead file #include<math.h>
③Pay attention to multiple sets of input

C language code:

#include<stdio.h>
#include<math.h>
int main()
{
    
    
	double x1,y1,x2,y2;
	while(~scanf("%lf %lf %lf %lf", &x1, &y1, &x2, &y2))
		printf("%.2lf\n",sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)));
	return 0;
}

C++ code:

#include<bits/stdc++.h>
using namespace std;
int main()
{
    
    
	double x1, y1, x2, y2;
	while(cin >> x1 >> y1 >> x2 >> y2)
		printf("%.2lf\n", sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)));
	return 0;
}

Guess you like

Origin blog.csdn.net/qq_44826711/article/details/112860737