#include<stdio.h>
#include<stdlib.h>
#include<math.h>
typedef struct point{
double x;//x坐标
double y;//y坐标
int n;//属于哪个吉
char label[10];//点标号
}Point;
int main(){
int n;
int i, j, k = 0, l = 0;
int m;//点的个数
double sq;
double min = 65535;//存储最小的点距离
int pos;//标记最小点集
char c;
Point *center;//存储中心点
Point *pot;//存储坐标点
double *dis;//存储距离的
printf("输入中心点的个数:\n");
scanf("%d", &n);
getchar();
for(i = 0; i < n; i++){//分配空间
center = calloc(n, sizeof(struct point));
dis = calloc(n, sizeof(double));
if(center == NULL || dis == NULL){
printf("calloc() error\n");
exit(1);
}
}
for(i = 0; i < n; i++){
printf("输入第%d个中心点的坐标,usage:a1 (4.2,5.3)\n", (i + 1));
scanf("%s (%lf,%lf)", &(center[i].label), &(center[i].x), &(center[i].y));
getchar();
}
for(i = 0; i < n; i++){
printf("%s(%.2f,%.2f)\n", center[i].label, center[i].x, center[i].y);
}
printf("请输入一共有几个点:\n");
scanf("%d", &m);
getchar();
for(i = 0; i < m; i++){//分配空间
pot = calloc(m, sizeof(struct point));
if(pot == NULL){
printf("error\n");
exit(1);
}
}
for(i = 0; i < m; i++){
printf("请输入第%d个点的坐标usage:a1 (4.2,5.3)\n", i+1);
scanf("%s (%lf,%lf)", &pot[i].label, &pot[i].x, &pot[i].y);
getchar();
}
for(i = 0; i < m; i++){
printf("%s(%.2f,%.2f)\n", pot[i].label, pot[i].x, pot[i].y);
}
while(k < 3){//迭代3次
printf("第%d次迭代\n", k+1);
for(i = 0; i < m; i++){
min = 65535;
printf("%s", pot[i].label);
for(j = 0; j < n; j++){
dis[j] = sqrt(pow((pot[i].x - center[j].x), 2) + pow((pot[i].y - center[j].y), 2));
//printf("点(%.2lf,%.2lf)距离中心点为(%.2lf,%.2lf)的距离为%.3lf\n", pot[i].x, pot[i].y, center[j].x, center[j].y, dis[j]);
printf(" 和%s相距%.3lf", center[j].label, dis[j]);
if(min > dis[j]){
min = dis[j];
pos = j;
pot[i].n = j;//存储他的分类
}
}
printf("\n");
}
//计算新的中心点
for(i = 0; i < n; i++){//清空原先的中心点的值
center[i].x = 0;
center[i].y = 0;
center[i].n = 0;
}
for(i = 0; i < m; i++){
center[pot[i].n].x += pot[i].x;
center[pot[i].n].y += pot[i].y;
center[pot[i].n].n++;//记下有几个属于自己的点
}
for(i = 0; i < n; i++, l = 0){
printf("\n%s集的元素:(", center[i].label);
for(j = 0; j < m; j++){
if(i == pot[j].n){
printf("%s", pot[j].label);
l++;
if(center[i].n > l){
printf(", ");
}
}
}//end for
printf(")");
}
printf("\n");
for(i = 0; i < n; i++){
center[i].x = center[i].x/center[i].n;
center[i].y = center[i].y/center[i].n;
}
k++;
getchar();
}
return 0;
}
K-Means算法C语言实现
4星 · 超过85%的资源 需积分: 27 178 浏览量
2011-12-02
13:07:35
上传
评论 1
收藏 130KB ZIP 举报
过往记忆
- 粉丝: 4321
- 资源: 278
最新资源
- 永宏PLC例程源码东芝350T压铸机PLC程序
- Visual Basic语言教程.docx
- 永宏PLC例程源码18层永宏电梯程序
- Scratch语言教程.docx
- (资源包名是松下不必介意实际是台达)台达PLC例程源码自制收线架台达PLC程序(有注释)与威沦触摸屏程序
- Rust语言教程.docx
- (资源包名是松下不必介意实际是台达)台达PLC例程源码用台达PLC485通信控制11台英威腾变频启动停止速度设定
- (资源包名是松下不必介意实际是台达)台达PLC例程源码用台达EH2-40PLC两台控制5台台达ASDA-B伺服,天任文本作对话的
- (资源包名是松下不必介意实际是台达)台达PLC例程源码液压切块机程序
- (资源包名是松下不必介意实际是台达)台达PLC例程源码压瓦机
资源上传下载、课程学习等过程中有任何疑问或建议,欢迎提出宝贵意见哦~我们会及时处理!
点击此处反馈