求两点之间的距离,类中有静变量和静态方法

已调试可运行,但需要改进

package test;

public class Point {

double x,y;
static double d;
Point(double a,double b){
x = a;
y = b;
}

void TestPoint(Point p1,Point p2){
x = (p1.x + p2.x)/2;
y = (p1.y + p2.y)/2;
System.out.println("(" + x + ","+ y + ")");
}

static void distance(Point p1,Point p2){
d = Math.sqrt((p1.x - p2.x)*(p1.x - p2.x) + (p1.y - p2.y)*(p1.y - p2.y));
System.out.println(d);
}
public static void main(String[] args) {

Point p1 = new Point(0,0);
Point p2 = new Point(1,3);
Point.distance(p1, p2);
}


}
好的,我来为您解答。 首先,我们需要定义一个 `Point` 类,表示一个的坐标。这个类可以有两个私有成员变量 `x` 和 `y`,分别表示横坐标和纵坐标。 然后,我们可以在 `Point` 类中定义一个公有成员函数 `distanceTo`,用于计算当前和另一个之间距离。这个函数接受一个 `Point` 类型的参数,表示另一个。函数的实现可以使用勾股定理,计算两点之间距离。 接下来,我们可以使用友元函数来计算两个之间距离。友元函数是在类外部定义的函数,但可以访问类的私有成员。我们可以在 `Point` 类中声明一个友元函数 `distanceBetween`,用于计算两个之间距离。这个函数接受两个 `Point` 类型的参数,分别表示两个。函数的实现可以直接调用 `distanceTo` 函数,计算出两个之间距离。 最后,在主函数中,我们可以创建两个 `Point` 对象,分别表示两个,并调用 `distanceTo` 函数和 `distanceBetween` 函数,计算出两个之间距离。 下面是代码示例: ```cpp #include <iostream> #include <cmath> using namespace std; class Point { private: double x, y; // 的坐标 public: Point(double _x, double _y): x(_x), y(_y) {} double distanceTo(Point p) { return sqrt(pow(x - p.x, 2) + pow(y - p.y, 2)); } friend double distanceBetween(Point p1, Point p2); }; double distanceBetween(Point p1, Point p2) { return p1.distanceTo(p2); } int main() { Point p1(0, 0); Point p2(3, 4); cout << "The distance between (" << p1.distanceTo(p2) << ")" << endl; cout << "The distance between (" << distanceBetween(p1, p2) << ")" << endl; return 0; } ``` 运行结果: ``` The distance between (5) The distance between (5) ``` 另外,我们也可以将 `distanceBetween` 函数定义为 `Point` 类的静态成员函数,这样就不需要使用友元函数了。下面是代码示例: ```cpp #include <iostream> #include <cmath> using namespace std; class Point { private: double x, y; // 的坐标 public: Point(double _x, double _y): x(_x), y(_y) {} double distanceTo(Point p) { return sqrt(pow(x - p.x, 2) + pow(y - p.y, 2)); } static double distanceBetween(Point p1, Point p2) { return p1.distanceTo(p2); } }; int main() { Point p1(0, 0); Point p2(3, 4); cout << "The distance between (" << p1.distanceTo(p2) << ")" << endl; cout << "The distance between (" << Point::distanceBetween(p1, p2) << ")" << endl; return 0; } ``` 运行结果: ``` The distance between (5) The distance between (5) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值