使用结构定义函数以计算两点之间的欧几里德距离时遇到错误

Error encountered while defining a function to calculate the Euclidean distance between two points using a struct

我创建了一个函数来计算 C 中两点之间的欧氏距离(写在 Codeblocks 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)

还有一点就是在使用前需要declare/define函数

要访问结构中的值,您可以使用点表示法,而不是对其进行索引。所以你需要使用 p1.x 而不是 p1[0].

在return之后的任何语句都不是运行,所以你的打印语句在函数中不会是运行。

以下是在 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 %.3f\n",distance);
    return distance;
};

正如另一个答案中所说,如果您从某本书上了解 C 语法的基础知识,那将是很好的。

除了 好的回答...

... 而不是使用 double 函数来解决 float 问题,而是使用 float 函数。放弃铸件。

//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));