📄 c_av.cpp
字号:
/*********************************************************
//C_均值法
//许娇龙
//2007 3/10
**********************************************************/
#include <iostream.h>
#include <math.h>
#include "link.h"
#include "node.h"
#define c 2//类数
#define n 2//向量维数
#define m 20//样本个数
struct x
{
int x1;
int x2;
};
LinkedList<x> A;
LinkedList<x> B;
//判断前后两次类心是否相等
int Zeq(double Z[c][n],double ZZ[c][n])
{
int i,j;
for(i=0;i<c;i++)
for(j=0;j<n;j++)
{
if(Z[i][j]!=ZZ[i][j])
return 0;
}
return 1;
}
//找出向量到到类心的最小距离,插入相应类
void Insert_c(int x1,int x2,double Z[2][2])
{
double d1,d2;
x item;
item.x1=x1;
item.x2=x2;
d1=sqrt((double)((x1-Z[0][0])*(x1-Z[0][0])+(x2-Z[0][1])*(x2-Z[0][1])));
d2=sqrt((double)((x1-Z[1][0])*(x1-Z[1][0])+(x2-Z[1][1])*(x2-Z[1][1])));
if(d1<=d2)//插入类一
{
A.InsertAt(item);
}
else
{
B.InsertAt(item);
}
}
//计算类中向量个数
int Counterno_X(LinkedList<x> &C)
{
int no=0;
C.Reset();
while(!C.EndOfList())
{
no++;
C.Next();
}
cout<<no<<endl;
return no;
}
//计算新类心
void CounterZ(LinkedList<x> &C,double ZZ[2])
{
ZZ[0]=0;
ZZ[1]=0;
int z1,z2;
z1=0;z2=0;
int n1;
C.Reset();
while(!C.EndOfList())
{
z1+=C.Data().x1;
z2+=C.Data().x2;
C.Next();
}
n1=Counterno_X(C);
ZZ[0]=(double)z1/n1;
ZZ[1]=(double)z2/n1;
}
void print(LinkedList<x> &A,int cc)
{
cout<<"类"<<cc<<"为:"<<endl;
A.Reset();
if (A.EndOfList()) cout<<"EndOfList\n";
while(!A.EndOfList())
{
cout<<"("<<A.Data().x1<<","<<A.Data().x2<<")+";
A.Next();
}
cout<<endl;
}
void main()
{
double Z[c][n],ZZ[c][n];//各类类心
int x1[m]={0,1,0,1,2,1,2,3,6,7,8,6,7,8,9,7,8,9,8,9};
int x2[m]={0,0,1,1,1,2,2,2,6,6,6,7,7,7,7,8,8,8,9,9};
Z[0][0]=x1[0];
Z[0][1]=x2[0];
Z[1][0]=x1[1];
Z[1][1]=x2[1];
for(int j0=0;j0<c;j0++)
for(int j1=0;j1<n;j1++)
{
ZZ[j0][j1]=Z[j0][j1];
}
do {
A.ClearList();
B.ClearList();
for(int j0=0;j0<c;j0++)
for(int j1=0;j1<n;j1++)
{
Z[j0][j1]=ZZ[j0][j1];
}
cout<<endl<<"类心:";
cout<<"("<<Z[0][0]<<","<<Z[0][1]<<") "<<"("<<Z[1][0]<<","<<Z[1][1]<<") "<<endl;
//分类
for(int i=0;i<m;i++)
{
int x01,x02;
x01=x1[i];
x02=x2[i];
Insert_c(x01,x02,Z);
}
//计算新类心
double _z[2];
CounterZ(A,_z);
ZZ[0][0]=_z[0];
ZZ[0][1]=_z[1];
CounterZ(B,_z);
ZZ[1][0]=_z[0];
ZZ[1][1]=_z[1];
cout<<endl<<"类心new:";
cout<<"("<<ZZ[0][0]<<","<<ZZ[0][1]<<") "<<"("<<ZZ[1][0]<<","<<ZZ[1][1]<<") "<<endl;
}while(!Zeq( Z, ZZ));
print(A,1);
print(B,2);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -