计算两点间的距离
Problem Description
输入两点坐标(X1,Y1),(X2,Y2),计算并输出两点间的距离。
Input
输入数据有多组,每组占一行,由4个实数组成,分别表示x1,y1,x2,y2,数据之间用空格隔开。
Output
对于每组输入数据,输出一行,结果保留两位小数。
Sample Input
0 0 0 1
0 1 1 0
Sample Output
1.00
1.41
Author
lcy
Source
C语言程序设计练习(一)
解题思路
利用三角形求斜边公式进行计算,注意读入数据为实数,这里使用了double。
相关数学公式:
1.sqrt:求根。
例:sqrt(n)
2.pow:求方。
例:pow(n,2)
3.fabs:求绝对值。
例:fabs(n)。
tips:abs用于整数,fabs用于实数。
AC
#include<iostream>
using namespace std;
int main()
{
double x1, y1, x2, y2;
while(cin>>x1>>y1>>x2>>y2){
printf("%.2lf\n",sqrt(pow(fabs(x1 - x2), 2) + pow(fabs(y1 - y2), 2)));
}
return 0;
}
2024.02.03
解题思路
使用float精度已经足够
AC
#include<iostream>
#include<cmath>
#include<stdlib.h>
#include<math.h>
using namespace std;
int main(void) {
float x1, y1, x2, y2;
while (scanf("%f %f %f %f", &x1, &y1, &x2,&y2) != EOF) {
printf("%.2f\n", sqrt(pow(fabs(x1-x2),2)+ pow(fabs(y1 - y2), 2)));
}
return 0;
}