平面有100个点,任意两点可以构成一个线段。编一个程序,输出在构成的所有线段中,长度最长的线段长度。两点(x1,y1),(x2,y2)之间的距离公式为:
D=√(x1-x2)^2+(y1-y2)^2
解题思路:
这样的几何题还是比较友好的。点乘叉乘感觉就像是在考数学,还得背公式。
这道题如果只是比较距离可以不开根号,要求输出距离就要开根号了。
代码如下:
#include<stdio.h>
#include<math.h>
double dist(int x1,int y1,int x2,int y2)
{
return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y1));
}
int main()
{
int x[100]={
-10,-1,2,3,-99,234,34,32,19,83,
-10,-1,2,3,-99,234,34,32,19,83,
-10,-1,2,3,-99,234,34,32,19,83,
-10,-1,2,3,-99,234,34,32,19,83,
-10,-1,2,3,-99,234,34,32,19,83,
-10,-1,2,3,-99,234,34,32,19,83,
-10,-1,2,3,-99,234,34,32,19,83,
-10,-1,2,3,-99,234,34,32,19,83,
-10,-1,2,3,-99,234,34,32,19,83,
-10,-1,2,3,-99,234,34,32,19,83
};
int y[100]={
-10,-1,2,3,-99,234,34,32,19,83,
-10,-1,2,3,-99,234,34,32,19,83,
-10,-1,2,3,-99,234,34,32,19,83,
-10,-1,2,3,-99,234,34,32,19,83,
-10,-1,2,3,-99,234,34,32,19,83,
-10,-1,2,3,-99,234,34,32,19,83,
-10,-1,2,3,-99,234,34,32,19,83,
-10,-1,2,3,-99,234,34,32,19,83,
-10,-1,2,3,-99,234,34,32,19,83,
-10,-1,2,3,-99,234,34,32,19,83
};
double maxx=-1;
int maxi,maxj;
for(int i=0;i<99;i++)
{
for(int j=i+1;j<100;j++)
{
double dis=dist(x[i],y[i],x[j],y[j]);
if(dis>maxx)
{
maxx=dis;
maxi=i;
maxj=j;
}
}
}
printf("%lf (%d,%d),(%d,%d)\n",maxx,x[maxi],y[maxi],x[maxj],y[maxj]);
return 0;
}