📄 k.cpp
字号:
// k.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream.h>
#include "math.h"
class CSwatch
{//样本类
public:
void SetSwatch();
int clustering;
double GetDistance(CSwatch d);
double x,y;
};
void CSwatch::SetSwatch()
{//初始化样本
cout<<"请输入各分量的值";
double q,w;
cin>>q;
x=q;
cin>>w;
y=w;
clustering=0;
}
double CSwatch::GetDistance(CSwatch d)
{//计算两样本间距离
double a,b;
a=(x-d.x)*(x-d.x)+(y-d.y)*(y-d.y);
b=sqrt(a);
return b;
}
int main(int argc, char* argv[])
{
double sumx[100];
double sumy[100];
double dis;
int no[100],op,sum=0;
for(int ne=0;ne<100;ne++)
{
sumx[ne]=0;
sumy[ne]=0;
no[ne]=0;
}
int n,m;
cout<<"输入样本的个数:";
cin>>n;
cout<<"输入聚类中心个数";
cin>>m;
if(m>n||n>100||m>10)
{
cout<<"输入错误,输入聚类中心数大于样本数"<<endl;
cout<<"或输入的样本数或聚类中心数大于100,请重新输入:";
}
CSwatch cswatch[100];
CSwatch center[100];
CSwatch newcenter[100];
for(int i=0;i<n;i++)
cswatch[i].SetSwatch();
for(int j=0;j<m;j++)
center[j]=cswatch[j];
for(int k=0;k<n;k++)
{ dis=10000;
for(int l=0;l<m;l++)
if(cswatch[k].GetDistance(center[l])<dis)
{
dis=cswatch[k].GetDistance(center[l]);
cswatch[k].clustering=l;
}
}
for(int p=0;p<m;p++)
{
for(int r=0;r<n;r++)
{
if(cswatch[r].clustering==p)
{
sumx[p]=sumx[p]+cswatch[r].x;
sumy[p]=sumy[p]+cswatch[r].y;
no[p]++;
newcenter[p].x=sumx[p]/no[p];
newcenter[p].y=sumy[p]/no[p];
}
}
}
for(i=0;i<m;i++)
{
if(newcenter[i].x==center[i].x&&newcenter[i].y==center[i].y)
sum++;
cout<<sum<<endl;
if(sum==m)
op=0;
else
{
op=1;
for(int i=0;i<m;i++)
center[i]=newcenter[i];
}
}
while(0);
{
for(int k=0;k<n;k++)
{
dis=10000;
for(int l=0;l<m;l++)
if(cswatch[k].GetDistance(center[l])<dis)
{
dis=cswatch[k].GetDistance(center[l]);
cswatch[k].clustering=l;
}
}
for(int p=0;p<m;p++)
for(int r=0;r<n;r++)
if(cswatch[r].clustering==p)
{
sumx[p]=sumx[p]+cswatch[r].x;
sumy[p]=sumy[p]+cswatch[r].y;
no[p]++;
newcenter[p].x=sumx[p]/no[p];
newcenter[p].y=sumy[p]/no[p];
}
for(i=0;i<m;i++)
if(newcenter[i].x==center[i].x&&newcenter[i].y==center[i].y)
sum++;
if(sum==m)
op=0;
else
{
op=1;
for(int i=0;i<m;i++)
center[i]=newcenter[i];
}
}
for(i=0;i<m;i++)
{
cout<<"属于第"<<i+1<<"类的有以下样本:"<<endl;
for(int j=0;j<n;j++)
{
if(cswatch[j].clustering==i)
cout<<"第"<<j+1<<"号样本"<<endl;
}
}
return 0;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -