js创建一个函数getDistance(x1,y1,x2,y2),打印两点之间的距离
时间: 2023-04-03 14:03:25 浏览: 92
可以这样实现:
function getDistance(x1, y1, x2, y2) {
var distance = Math.sqrt(Math.pow((x2 - x1), 2) + Math.pow((y2 - y1), 2));
console.log("两点之间的距离为:" + distance);
}
调用函数时,传入两点的坐标即可,例如:
getDistance(0, 0, 3, 4); // 输出:两点之间的距离为:5
相关问题
实现1个简单的二维点类。构造函数可以用初始化列表实现对数据成员的初 始化。 (1)实现各个成员函数。 (2)实现Point 类中的成员函数getDistance,计算两点之间距离。 (3)定义普通函数getDistance,计算2 点之间距离 从键盘输入两点的坐标,分别用成员函数和普通函数计算这两点的距离。已知部分代码为#include <iostream> #include <cmath> using namespace std; class Point { public: Point( double newX=0, double newY=0); void setValue(double newX, double newY); double getX( ); double getY(); double getDistance(Point& p2); //成员函数计算距离 private: double x, y; }; double getDistance(Point& p1, Point& p2); //普通函数计算距离 int main() { Point p1,p2; double x1,y1,x2,y2; cin>>x1>>y1>>x2>>y2; p1.setValue(x1,y1); p2.setValue(x2,y2); double dis1 = p1.getDistance(p2); //成员函数版本计算 cout<<"Distance: "<<dis1<<endl; double dis2 = getDistance(p1,p2); //普通函数版本计算 cout<<"Distance: "<<dis2<<endl; return 0; } /* 请在这里填写答案 */
答案如下:
```
#include <iostream>
#include <cmath>
using namespace std;
class Point {
public:
Point(double newX = 0, double newY = 0) : x(newX), y(newY) {} // 初始化列表初始化数据成员
void setValue(double newX, double newY) {
x = newX;
y = newY;
}
double getX() {
return x;
}
double getY() {
return y;
}
double getDistance(Point& p2) { // 成员函数计算距离
double dx = x - p2.getX();
double dy = y - p2.getY();
return sqrt(dx * dx + dy * dy);
}
private:
double x, y;
};
double getDistance(Point& p1, Point& p2) { // 普通函数计算距离
double dx = p1.getX() - p2.getX();
double dy = p1.getY() - p2.getY();
return sqrt(dx * dx + dy * dy);
}
int main() {
Point p1, p2;
double x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
p1.setValue(x1, y1);
p2.setValue(x2, y2);
double dis1 = p1.getDistance(p2); // 成员函数版本计算
cout << "Distance: " << dis1 << endl;
double dis2 = getDistance(p1, p2); // 普通函数版本计算
cout << "Distance: " << dis2 << endl;
return 0;
}
```
如何计算三维空间中两点之间的距离?
在三维空间中,两点之间的距离可以使用勾股定理来计算。具体步骤如下:
1.定义一个 Point 类,该类包含三个属性:x、y 和 z,分别表示三维空间中的坐标。
2.在 Point 类中定义一个 getDistance 函数,该函数接受另一个 Point 类型的参数,用于计算两点之间的距离。
3.在 getDistance 函数中,使用勾股定理计算两点之间的距离,公式为:d = sqrt((x2-x1)^2 + (y2-y1)^2 + (z2-z1)^2),其中 sqrt 表示平方根。
4.最后,实例化两个 Point 对象,调用 getDistance 函数计算它们之间的距离。
下面是一个 Python 代码示例:
```python
import math
class Point:
def __init__(self, x, y, z):
self.x = x
self.y = y
self.z = z
def getDistance(self, other):
dx = self.x - other.x
dy = self.y - other.y
dz = self.z - other.z
return math.sqrt(dx*dx + dy*dy + dz*dz)
# 实例化两个 Point 对象
p1 = Point(1, 2, 3)
p2 = Point(4, 5, 6)
# 计算两点之间的距离
distance = p1.getDistance(p2)
print(distance)
```
运行结果为:5.196152422706632