求一条直线经过一个直角坐标系里m个点最多点的点数

这篇博客探讨了在直角坐标系中,如何找到一条通过最多点的直线的方法。通过对P0到P(m-1)各点进行计算,找出与后续点形成直线并计算满足条件的点的数量,从而确定最多点的直线。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

typedef struct POINT
{
  double x;
  double y;
}Point;


输入点数和各个点的坐标:
void hjd_init_points()
{
  printf("please input the number of points:\n");
  int nM=0, nPos=0;
  scanf("%d", &nM);
  Point myPoints[nM];

  for(nPos=0;nPos<nM;nPos++)
  {
    printf("\nplease input the No.%d point:(like x,y)\n", nPos);
    scanf("%lf,%lf", &myPoints[nPos].x, &myPoints[nPos].y);
  }
  printf("\nComplete input the Points, and now to calculate the max number of points that a line can cross...\n");
  int nMax=hjd_Get_Line_Cross_Points(myPoints, nM);
  printf("\nThe max number of points that a line can cross = %d\n", nMax);
}

把坐标数组和数组的长度作为参数传入。

P0,P1,...,P(m-1)个点,从第一个点开始,依次求与后面某个点之间直线的方程,然后从 P0 开始计算满足该直线方程的点的个数,与历史记录比较,记录大的,最后就得到最多的点数,返回。

int hjd_Get_Line_Cross_Points(Point myPoints[], int m)
{
  int i=0, j=0;
  int nMaxCrossPoint=0;
  for(i=0;i<(m-1);i++)
  {
    for(j=i+1;j<m;j++)
    {
      double k = ((myPoints[i].y)-(myPoints[j].y))/((myPoints[i].x)-(myPoints[j].x));
      double b = myPoints[i].y-k*myPoints[i].x;
      printf("\nThe Line form:y=%f*x+%f\n", k, b);
      int nCount=0;
      for(int nPos=0;nPos<m;nPos++)
      {
        if(myPoints[nPos].y==(k*myPoints[nPos].x+b))
        {
          nCount++;
        }
        if (nCount>nMaxCrossPoint)
          nMaxCrossPoint=nCount;
      }
    }
  }
  return(nMaxCrossPoint);
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值