使用 C 中的结构查找向量积



我需要编写函数来使用 C 中的结构计算三个向量的向量积。我编写了正确的函数,但我不知道如何打印结果。 结构对我来说是新的。

我收到一个错误:

格式 '%g' 需要类型为 'double' 的参数,但参数 2 的类型为 '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;
}

在这一行中:

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

vector_product()返回类型为Vektor3d的对象。函数printf()不知道如何打印此对象。您必须调用printf()并仅将其可以处理的类型(例如整数,双精度等)传递给它。

要解决此问题,只需将结果对象存储在变量中,然后将其组件传递给printf()。那是

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

最新更新