要求:语言要求纯C语言, 知识点要求:读文件,结构体,动态分配内存,数组,指针,函数,循环,条件判断。
代码描述:
#include <stdio.h>
#include <malloc.h>
#include <math.h>
#include <string.h>
struct Coordinator{
int x;
int y;
};
typedef struct City{
char name[5];
struct Coordinator place;
}Point;
void myinprint(FILE *p,Point *q,int n);
void myoutprint(Point *q,int n);
Point* readfile();
double distance(Point *city,char a[],char b[],int n);
void closest(Point city[]);
double luJin(Point city[],char array[],int n);
void disAll(Point city[]);
int n;
int main() {
Point *point = readfile();
char array[6] = "ABCD";
char a[5],b[5];
printf("\n求距离 请输入一对顶点如(A B):");
scanf("%s %s",a,b);
printf("%s和%s的距离是:%.3lf",a,b,distance(point,a,b,n));
closest(point);
luJin(point,array,n);
disAll(point);
return 0;
}
Point* readfile(){
FILE *fp = NULL;
fp = fopen("test1.txt","r");
fscanf(fp,"%d",&n);
Point *p = (Point*)malloc(n*sizeof(Point));
printf("有%d个城市\n",n);
myinprint(fp,p,n);
myoutprint(p,n);
return p;
}
void myinprint(FILE *p,Point *q,int n){
int i;
for(i=0;i<n;i++,q++)
fscanf(p,"%s%d%d",q->name,&q->place.x,&q->place.y);
}
void myoutprint(Point *q,int n){
int i;
for(i=0;i<n;i++,q++)
printf("%s\t%d\t%d\n",q->name,q->place.x,q->place.y);
}
double distance(Point city[],char a[],char b[],int n){
int i;
int x,x1;
int y,y1;
double c;
for(i=0;i<n;i++){
if(strcmp(city[i].name,a) == 0){
x = city[i].place.x;
y = city[i].place.y;
}
if(strcmp(city[i].name,b) == 0){
x1 = city[i].place.x;
y1 = city[i].place.y;
}
}
c = sqrt((double)((x-x1)*(x-x1) + (y-y1)*(y-y1)));
return c;
}
void closest(Point city[]){
int i=0,j=0;
double min = distance(city,city[0].name,city[1].name,n);
double c = 0;
char M[5],N[5];
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
c = distance(city,city[i].name,city[j].name,n);
if(c<min){
min = c;
strcpy(M,city[i].name);
strcpy(N,city[j].name);
}
}
}
printf("\n最近的两个坐标是:%s和%s的距离是:%.3f",M,N,min);
}
double luJin(Point city[],char array[],int n){
int i,j;
char a[5] ;
char b[5] ;
double K=0;
static double sum[6];
for(i=0;i<4;i++){
a[0] = array[i];
a[1] = '\0';
b[0] = array[i+1];
b[1] = '\0';
sum[i] = distance(city,a,b,n);
K += sum[i];
}
printf("总里程%.3f\n",K);
}
void disAll(Point city[]){
int i,j,k=0;
static double num[10],temp;
for(i=0;i<n;i++){
for(j=i+1;j<n;j++){
num[k] = distance(city,city[i].name,city[j].name,n);
printf("num[%d]=%.3f\n",k,num[k]);
k++;
}
}
printf("\n**********************\n");
for(i=0;i<10;i++){
for(j=0;j<10-i-1;j++){
if(num[j] > num[j+1]){
temp = num[j+1];
num[j+1] = num[j];
num[j] = temp;
}
}
}
for(i=0;i<10;i++){
printf("num[%d]=%.3f\n",i,num[i]);
}
printf("\n**********************\n");
printf("num[%d]=%.3f\n",9/2,num[9/2]);
printf("num[%d]=%.3f\n",9/2+1,num[9/2+1]);
}
结果描述: 要是要求模块功能简单,那就把我的代码注释几行即可; 第30行和第106行注释掉 效果显示如下
详解请关注牛牛,私聊给你过程解析!
但是为了让各位同学有优秀的编程能力,增强动手能力,此代码虽然是完整程序,还是请先独立思考,再拿此程序作为参考,相信你会有更好的解题过程,要是有不妥之处,各位请多多指正,多多包涵
|