我创建了一个函数来计算C中两点之间的欧几里得距离(写在代码块IDE中(,但出现了一些错误:
error: expected ')' before 'p1'|
error: expected expression before ',' token|
上述错误发生在函数float Euclidean(struct point p1,struct point p2)
内部
以下是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct point { float x, y, z; };
int main() {
struct point p1 = { 2.1, 3.0, 1.2 };
struct point p2 = { 0.5, 0.5, -0.2 };
float Euclidean(struct point p1, struct point p2);
return 1;
}
float Euclidean(struct point p1, struct point p2) {
float distance;
distance = (float)sqrt((float)powf((struct point p1[0] - struct point p2[0]), 2)+/n
(float)powf((struct point p1[1] - struct point p2[1]), 2)+/n
(float)powf((struct point p1[2] - struct point p2[2]), 2));
return distance;
printf("the distance between p1 and p2 is %.3f", distance);
};
我怀疑我的打字有问题,但我不明白为什么(我对C还比较陌生(。有人能给我一些提示吗?
提供的代码中几乎没有错误。您不需要将struct point
注释添加到变量的用法中。因此,无论您在哪里需要使用变量,都可以像Euclidean(p1, p2)
一样直接引用它们
另一点是在使用函数之前需要声明/定义它
对于访问结构中的值,您使用点表示法,而不是对其进行索引。因此,您需要使用p1.x
而不是p1[0]
。
返回后的任何语句都不会运行,因此打印语句不会在函数中运行。
以下是在GCC 9.3.0中编译和运行的更正代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
struct point {float x, y, z; };
float Euclidean(struct point p1,struct point p2);
int main()
{
struct point p1 = {2.1,3.0,1.2};
struct point p2 = {0.5,0.5,-0.2};
float distance = Euclidean(p1, p2);
return 0;
}
float Euclidean(struct point p1,struct point p2){
float distance;
distance = (float)sqrt((float)pow((p1.x-p2.x),2)+
(float)pow((p1.y-p2.y),2)+
(float)pow((p1.z-p2.z),2));
printf("the distance between p1 and p2 is %.3fn",distance);
return distance;
};
正如在另一个答案中所说,如果你能从一些书中了解C语法的基础知识,那就太好了。
除了@e_一个好答案。。。
使用float
函数而不是针对float
问题使用double
函数。放下铸件。
//float distance;
//distance = (float)sqrt((float)pow((p1.x-p2.x),2)+
// (float)pow((p1.y-p2.y),2)+
// (float)pow((p1.z-p2.z),2));
float distance = sqrtf(powf((p1.x - p2.x),2) +
powf((p1.y - p2.y),2) +
powf((p1.z - p2.z),2));