c - 包含 'double' 数组的结构中的 Scanf 不起作用?

标签 c arrays struct

所以我必须使用结构和 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。

最佳答案

结构成员xy 数组各只能包含一个元素。但是您正在读取 2 个元素作为输入。

在 C 中,数组索引的范围从 0N-1。由于越界访问,您的代码有未定义的行为

增加数组大小:

 struct _point2d
    {
       double x[2]
       double y[2];
    };

关于c - 包含 'double' 数组的结构中的 Scanf 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41793168/

相关文章:

当数据复制/扫描/读取到未初始化的指针时崩溃或 "segmentation fault"

将字符串数组转换为 C 中的十六进制数

javascript - 纯JS获取Json数组

python - 为什么 python 在此处使用嵌套循环时会打印奇怪的结果?

python - 构建 Cython 扩展时出现错误 : ‘PyThreadState’ {aka ‘struct _ts’ } has no member named ‘exc_type’ ; did you mean ‘curexc_type’ ?

matlab - 如何访问嵌套在 MATLAB 元胞数组中的结构数组的所有字段元素?

具有不同参数的函数的 C 冲突类型

c - 模拟 jg 指令(datalab 的 isGreater)

c - 在C中为两种不同的变量类型输入一次

php - 不要写入空数组字段