确定使用布尔函数在线路上的所有2D点线还是在C 中的所有圆

detemining if all the 2D points line on a line or a circle or not in c++ using boolean function

本文关键字:2D 在线 函数 布尔 路上      更新时间:2023-10-16

我已经制作了一个C 程序来读取文本文件的一些2D值(x,y)。我的代码如下:

#include<iostream>
#include<sstream>
#include<fstream>
using namespace std;
template <typename T>
class Node {
public:
    T data;
    Node<T>* next;
    Node<T>* previous;
    Node(T data) {
        this->data = data;
        this->next = NULL;
        this->previous = NULL;
    }
};
template <typename T>
class List {
public:
    int size;
    Node<T>* start;
    List() {
    start = NULL;
    size = 0;
}
Node<T>* insert(T data) {
    Node<T>* new_node = new Node<T>(data);
    new_node->next = start;
    new_node->previous = NULL;
    if (start != NULL) {
        start->previous = new_node;
    }
    start = new_node;
    size += 1;
    return new_node;
 }
};
class Point { 
public:
    double x;
    double y;
    Node<Point*>* points_node; 
    Point(double x, double y) {
    this->x = x;
    this->y = y;
  }
};
main()
{
    List<Point*>* input_points;
    input_points = new List<Point*>();
    ifstream ifs("input.txt");
    double x,y;
    ifs>>x>>y;
    while(!ifs.eof())
    {
        Point* p = new Point(x, y);
        input_points->insert(p);
        ifs>>x>>y;
    } 
   bool line=check_line(input_points); // boolean function not defined
   bool circle=check_circle(input_points); // boolean function not defined

} 

有什么方法可以编写布尔函数以确定所有点是否均位于线上还是在圆上?

输入文件格式如下:

5.0 10.0
10.0 10.0
15.0 10.0

您的列表和程序可以使用大量改进。

使用现有数据结构
您可以使用std::pair类创建Point

typedef std::pair<double> Point;

您也可以使用std::list而不是创建自己的(需要工作):

typedef std::list<Point> Point_List;

知道这一点,main函数变为:

int main(void)
{
  Point_List  data_points;
  ifstream    input("input.txt");
  if (!input)
  {
    cerr << "Error opening input.txtn";
    return EXIT_FAILURE;
  }
  double x, y;
  while (input >> x >> y)
  {
    Point p;
    p.first = x;
    p.second = y;
    data_points.push_back(p);
  }
  if (line_check(data_points))
  {
    //...
  }
  if (circle_check(data_points))
  {
    //...
  }
  cout << "nnPaused.  Press Enter to continue.n";
  cin.ignore(100000, 'n');
  return EXIT_SUCCESS;
}

您可以使用迭代器访问列表中的每个元素。搜索网络以查找" C 列表迭代示例"。

对于一条线,选择两个点并以y = mx b的形式从它们中得出一个方程(使用两个点求解m和b)点也满足方程式。如果没有,这些点并非全部在线上。

对于一个圆,方程形式为(x a)^2 (y b)^2 = r^2,因此再次取3点并求解a,b和r。然后看看其他点是否也满足该方程式。如果他们都这样做,那么点就在一个圆圈上。

我认为,阵列比链接列表更合适。您可以使用std :: vector。