Home > OS >  Find vector product using structures in C
Find vector product using structures in C

Time:02-10

I need to write function for calculating vector product of three vectors using structures in C. I have written function which works correct but I don't know how to print result. Structures are new to me.

I get an error:

format ‘%g’ expects argument of type ‘double’, but argument 2 has type ‘Vektor3d’ {aka ‘struct anonymous’}

#include <stdio.h>
typedef struct{
    double x,y,z;
}     Vektor3d;

Vektor3d vector_product(Vektor3d v1, Vektor3d v2)
{
    Vektor3d v3;
    v3.x=(v1.y*v2.z-v1.z*v2.y);
    v3.y=(v1.z*v2.x-v1.x*v2.z);
    v3.z=(v1.x*v2.y-v1.y*v2.x);
    return v3;
}

int main() {
   Vektor3d v1,v2;
    scanf("%lf %lf %lf", &v1.x, &v1.y, &v1.z);
    scanf("%lf %lf %lf", &v2.x, &v2.y, &v2.z);
    printf("%g", vector_product(v1, v2));
    return 0;
}

CodePudding user response:

In this line:

    printf("%g", vector_product(v1, v2));

vector_product() returns an object of type Vektor3d. The function printf() does not know how to print this object. You have to call printf() and pass to it only the types it can handle (e.g. integers, doubles, etc.)

To fix this, simply store the result object in a variable, then pass its components to printf(). That is,

int main() {
    Vektor3d v1,v2;
    Vektor3d v3;

    scanf("%lf %lf %lf", &v1.x, &v1.y, &v1.z);
    scanf("%lf %lf %lf", &v2.x, &v2.y, &v2.z);
    v3 = vector_product(v1, v2);          /* Save the return value in v3 */
    printf("%g %g %g", v3.x, v3.y, v3.z); /* pass the components of v3 to printf */
    return 0;
}
  • Related