所以我必须使用结构和 scanf 编写标量积 ((x1*y1)+(x2*y2))。 然而,我的程序只是跳过 y1 并将 y1 和 x2 计为相同的数字,即使我输入了完全不同的数字? 我做了以下事情:
struct _point2d
{
double x[1]; // this means x1 is x[0] and x2 is x[1]
double y[1];
};
double PscalarProduct( double a, double b, double c, double d )
{
printf("The scalar product ((x1*y1) + (x2*y2)) (whereas x1 = %lf,
y1 = %lf, x2 = %lf, y2 = %lf) is %lf\n", a, b, c, d, (( a*b ) + ( c*d )) );
}
int main()
{
struct _point2d Vector;
Vector.x[1];
Vector.y[1];
printf("Enter x1 and y1 \n");
scanf("%lf", &(Vector.x[0]));
scanf("%lf", &(Vector.y[0]));
printf("Enter x2 and y2 \n");
scanf("%lf", &(Vector.x[1]));
scanf("%lf", &(Vector.y[1]));
PscalarProduct(Vector.x[0], Vector.y[0], Vector.x[1], Vector.y[1]);
return 0;
}
但是,如果我使用数字 1[=x1] 2[=y1] 3[=x2] 4[=y2] 运行程序,我会收到以下文本:
The scalar product ((x1*y1) + (x2*y2)) (whereas x1 = 1.000000, y1 = 3.000000, x2 = 3.000000, y2 = 4.000000) is 15.000000
y1 和 x2 怎么可能是相同的数??? y1 应该是数字 2.00000。
最佳答案
结构成员x
和y
数组各只能包含一个元素。但是您正在读取 2 个元素作为输入。
在 C 中,数组索引的范围从 0
到 N-1
。由于越界访问,您的代码有未定义的行为。
增加数组大小:
struct _point2d
{
double x[2]
double y[2];
};
关于c - 包含 'double' 数组的结构中的 Scanf 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41793168/