c语言要求使用class,计算这两点之间的距离
时间: 2024-04-29 22:20:51 浏览: 9
C语言不支持class,但是可以使用结构体来模拟类的功能,以下是使用结构体计算两点之间距离的示例代码:
```
#include <stdio.h>
#include <math.h>
struct Point {
double x;
double y;
};
double distance(struct Point p1, struct Point p2) {
double dx = p1.x - p2.x;
double dy = p1.y - p2.y;
return sqrt(dx * dx + dy * dy);
}
int main() {
struct Point p1 = {1.0, 2.0};
struct Point p2 = {3.0, 4.0};
double d = distance(p1, p2);
printf("The distance between (%f, %f) and (%f, %f) is %f\n", p1.x, p1.y, p2.x, p2.y, d);
return 0;
}
```
相关问题
C语言计算两点之间的距离
以下是两种C语言计算两点之间距离的方法:
1.使用math库中的sqrt()函数和pow()函数
```c
#include <stdio.h>
#include <math.h>
int main()
{
float x1, y1, x2, y2, dist;
printf("请输入两点坐标(x1,y1,x2,y2):");
scanf("%f%f%f%f", &x1, &y1, &x2, &y2);
dist = sqrt(pow(x1 - x2, 2) + pow(y1 - y2, 2));
printf("两点之间的距离为:%.2f\n", dist);
return 0;
}
```
2.不使用math库中的函数
```c
#include <stdio.h>
int main()
{
float x1, y1, x2, y2, dist;
printf("请输入两点坐标(x1,y1,x2,y2):");
scanf("%f%f%f%f", &x1, &y1, &x2, &y2);
dist = sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
printf("两点之间的距离为:%.2f\n", dist);
return 0;
}
```
用C语言计算两点之间的距离
可以使用以下公式计算两点之间的距离:
distance = sqrt(pow((x2-x1),2) + pow((y2-y1),2));
其中,(x1,y1)和(x2,y2)分别是两个点的坐标,pow()函数用于计算平方,sqrt()函数用于计算平方根。