题目描述:
数据文件里面是用二进制编写的,里面放了一堆int 型的数,每个数占4个字节,每次读取两个,这两个数构成一个坐标。
(1)规定处于第一象限的数是有效点,(即x>0,y>0的坐标),问这么多点中有效点有多少个?
(2)现在用户从键盘输入一个坐标和一个数字K,设计算法输出K个离该坐标距离最近的点的坐标和每个坐标到该点的距离,写入到output.txt文件中
输入描述:
1、模拟数据下载网址,数据同2012年
https://download.csdn.net/download/tsc5214/11012209
2、控制台输入的数据:(1,1) 12
输出描述:
控制台输出内容:
读取的数据中有效点有13个
Output.txt
离点(1,1)12个最近点及之间距离分别是
(1,1),相距距离为0.000000
(4,3),相距距离为3.605551
(6,8),相距距离为8.602325
(8,6),相距距离为8.602325
(8,9),相距距离为10.630146
(8,9),相距距离为10.630146
(20,3),相距距离为19.104973
(22,77),相距距离为78.847955
(80,3),相距距离为79.025312
(90,2),相距距离为89.005618
(8,90),相距距离为89.274856
(90,10),相距距离为89.453899
代码:
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
int seekValidPoints(struct coordinate co[],int num,struct coordinate validco[]);
void seekNearPoints(struct coordinate validco[],int validnum);
struct coordinate{
int x;
int y;
};
int main(){
FILE *fp;
struct coordinate co[100];
struct coordinate validco[100];
int i=0;
int validnum=0;
if((fp=fopen("D:\\2019Post\\pat\\pat\\data2012.dat","r"))==NULL){
printf("can not open the file");
exit(0);
}
while(fread(&co[i].x,4,1,fp)){
fread(&co[i].y,4,1,fp);
i++;
}
fclose(fp);
validnum=seekValidPoints(co,i,validco);
printf("读取的数据中有效点有%d个\n",validnum);
seekNearPoints(validco,validnum);
return 0;
}
int seekValidPoints(struct coordinate co[],int num,struct coordinate validco[]){
int i,count=0;
for(i=0;i<num;i++){
if(co[i].x>0&&co[i].y>0){
validco[count].x=co[i].x;
validco[count].y=co[i].y;
count++;
}
}
return count;
}
void seekNearPoints(struct coordinate validco[],int validnum){
int k,i,j,s,d;
struct coordinate temp;
double store1;
struct coordinate store2;
double* distance;
FILE *fa;
scanf("(%d,%d)",&temp.x,&temp.y);
scanf("%d",&k);
if(k>validnum){
printf("输入K值超过有效点的个数");
return;
}
distance=(double*)malloc(validnum*sizeof(int));
for(i=0;i<validnum;i++){
distance[i]=sqrt((double)((temp.x-validco[i].x)*(temp.x-validco[i].x)+(temp.y-validco[i].y)*(temp.y-validco[i].y)));
}
for(j=1;j<validnum;j++)
for(s=0;s<validnum-j;s++){
if(distance[s]>distance[s+1]){
store1=distance[s];
distance[s]=distance[s+1];
distance[s+1]=store1;
store2=validco[s];
validco[s]=validco[s+1];
validco[s+1]=store2;
}
}
if((fa=fopen("D:\\2019Post\\pat\\pat\\Output2014.txt","w"))==NULL){
printf("can not open the file");
exit(0);
}
setbuf(fa,NULL);//关闭缓冲
fprintf(fa,"离点(%d,%d)%d个最近点及之间距离分别是\n",temp.x,temp.y,k);
for(d=0;d<k;d++){
fprintf(fa,"(%d,%d),相距距离为%lf\n",validco[d].x,validco[d].y,distance[d]);
}
fclose(fa);
}