如何分为两组?

时间:2011-04-17 02:31:54

标签: c

这里我在C代码中划分分组存在一些问题。下面是我的C代码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int main (){
int inp;
inp = 15;

signed int cx[15], cy[15];
cx[0] = 1;
cx[1] = 7;
cx[2] = -2;
cx[3] = -3;
cx[4] = -2;
cx[5] = -2;
cx[6] = -10;
cx[7] = 0;
cx[8] = -1;
cx[9] = 8;
cx[10] = 9;
cx[11] = 10;
cx[12] = -7;
cx[13] = 12;
cx[14] = 11;

cy[0] = -8;
cy[1] = -1;
cy[2] = -10;
cy[3] = -8;
cy[4] = -6;
cy[5] = -10;
cy[6] = 12;
cy[7] = 0;
cy[8] = 5;
cy[9] = -1;
cy[10] = 13;
cy[11] = -10;
cy[12] = 3;
cy[13] = 13;
cy[14] = 0;

int j;
printf ("\n Input (x,y) :\n\n");
for (j=0; j<inp; j++){
printf ("   X%d :(%d,%d)\n",(j+1),cx[j],cy[j]);}

printf ("\n Initial value of 2 centers :\n");
printf ("\n   Y1 = X1 : (%d,%d)\n",cx[0],cy[0]);
printf ("   Y2 = X2 : (%d,%d)\n",cx[1],cy[1]);

printf ("\n Objects-centers distance :\n\n");
for(j=2; j<inp; j++){
float dis1, dis2;
dis1 = sqrt((cx[j]-cx[0])*(cx[j]-cx[0])+(cy[j]-cy[0])*(cy[j]-cy[0]));
dis2 = sqrt((cx[j]-cx[1])*(cx[j]-cx[1])+(cy[j]-cy[1])*(cy[j]-cy[1]));
printf("   X%d -> Y1 : %.5f\t X%d -> Y2 : %.5f\n", (j+1), dis1, (j+1), dis2);}

printf ("\n Objects gouping :\n");

}

如何分为两组?第一组是最接近第一个中心点的点,第二组是最接近第二个中心点的点。

1 个答案:

答案 0 :(得分:0)

有很多方法可以解决这个问题。

最简单的是简单地创建第三个数组,其大小与前两个相同。每个元素将对应于每个cx / cy对,如果该对更靠近第一个点,则值为0;如果距离第二个点更近,则值为1

int result[15] = {0,1,0};  // points 2-14 initialized to 0

if (dis1 < dis2)
  result[j] = 0;
else
  result[j] = 1;

因此,如果您想查看点4是否更接近点0或点1,您只需检查result[4]的值。

相关问题