cmath.h

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


I created a function to calculate the Euclidean distance between two points in C (written in the Codeblocks IDE), however some errors occurred:

error: expected ')' before 'p1'|

error: expected expression before ',' token|

The errors above occurred inside the function float Euclidean(struct point p1,struct point p2)

Below is my code:

#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);
};

I suspect there is some issue with my typecasting, but I can't figure out why (I'm relatively new to C). Could someone give me some hints?


Solution

  • There are few mistakes in the provied code. You do not need to add struct point annotation to usages of variables. So wherever you need to use variable, you can directly reference them like Euclidean(p1, p2)

    Another point is you need to declare/define function before using it.

    For accessing value within a struct, you use dot notation, not index into it. So you need to use p1.x instead of p1[0].

    Any statement after return is not run, so your print statement will not be run in the function.

    Following is corrected code that compiles and run in 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;
    };
    

    As said in the other answer, it will be good if you understand the basics of C syntax from some book.