输入如下:每一行是居民点位置和人口数
5 5 2
5 35 2
10 27.5 2.5
15 5 2
15 15 3
15 40 2
17.5 25 3.5
20 15 4
25 30 4
25 45 2
30 10 4
35 20 5
40 5 3
42.5 25 6
45 35 5
52.5 42.5 5.5
55 35 4.5
55 5 4
57.5 10 3
输出如下:
Step=0.10L=1347.483601m_best.x=33.90m_best.y=21.60
// BestCenter.cpp : Defines the entry point for the console application. // #include "stdio.h" #include "stdafx.h" #include "stdlib.h" #include "math.h" struct RESIDENCE{ //存储每一个居民点的坐标和人口数 float x; float y; float p; }; struct POINT{ float x; float y; }; void main() { //重要变量 RESIDENCE *m_data; POINT m_best; float m_xmin, m_xmax, m_ymin, m_ymax; //居民点坐标中的最值 int m_count; //居民点的个数 double L = 99999999.9; //距离与人口数乘积的累加和 float step; //控制循环的步长 //其它变量 float temp1,temp2,temp3; int i; char m_file[]="best.txt"; float j,k; FILE *fp; //部分变量初始化 double temp=0.0; i=0; m_count=0; j=k=temp1=temp2=temp3=0.0; m_xmin=m_xmax=m_ymin=m_ymax=0.0; //提示用户输入循环的步长 printf("Please intput step= "); scanf("%f",&step); /* 读文件,将数据存入m_data中 */ if((fp=fopen(m_file,"r"))==NULL) { printf("Can not open this file.\n"); exit(0); } while(!feof(fp)) { fscanf(fp,"%f %f %f",&temp1,&temp2,&temp3); m_count++; } m_data=(RESIDENCE*)malloc(sizeof(RESIDENCE)*m_count); rewind(fp); while(!feof(fp)) { fscanf(fp,"%f %f %f",&m_data[i].x,&m_data[i].y,&m_data[i].p); i++; } fclose(fp); //将m_data中数据输出到屏幕 for(i=0;i<m_count;i++) printf("%3d %5.1f,%5.1f,%5.1f\n",i+1,m_data[i].x,m_data[i].y,m_data[i].p); //寻找m_data中坐标x和y的最大值及最小值 m_xmax=m_xmin=m_data[0].x; //min and max m_ymax=m_ymin=m_data[0].y; for(i=1;i<m_count;i++) { if(m_xmin>m_data[i].x) m_xmin=m_data[i].x; if(m_xmax<m_data[i].x) m_xmax=m_data[i].x; if(m_ymin>m_data[i].y) m_ymin=m_data[i].y; if(m_ymax<m_data[i].y) m_ymax=m_data[i].y; } //三重循环,寻找最优点的位置及L的最小值 for(j=m_xmin;j<m_xmax;j+=step) { for(k=m_ymin;k<m_ymax;k+=step) { for(i=0;i<m_count;i++){ temp+=m_data[i].p*sqrt(pow(m_data[i].x-j,2)+pow(m_data[i].y-k,2)); }//for(i=0;i<m_count;i++) if(temp<L) { L=temp; m_best.x=j; m_best.y=k; }//if(temp<L) temp=0.0; }//for(k=m_ymin;k<m_ymax;k=k+5) } printf("L=%.5f ;m_best.x=%.1f; m_best.y=%.1f\n",L,m_best.x,m_best.y); char m_out[]="result.txt"; if((fp=fopen(m_out,"w"))==NULL) { printf("Can not open this file.\n"); exit(0); } fprintf(fp,"Step=%.2fL=%.6fm_best.x=%.2fm_best.y=%.2f\n",step,L,m_best.x,m_best.y); fclose(fp); free(m_data); }