gpt4 book ai didi

c++ - 数组未按 C++ 中的预期填充

转载 作者:行者123 更新时间:2023-11-28 00:27:00 24 4
gpt4 key购买 nike

<分区>

我昨天才开始尝试学习 C++,我近期的目标之一是制作一个矩阵乘法函数。

在尝试之前,我想了解一下数组的工作原理,所以我编写了一个简单的程序,该程序应该创建两个数组来表示 3D 空间中的(数学) vector 并获取它们的点积。下面是我写的代码。

/*Initializing two vectors, v1 and v2*/
int v1[3] = { 0 };
int v2[3] = { 0 };

int sum = 0; //This will become the sum for the dot product

int i=0; //counter for the following loop
for(; i<3; ++i)
v1[i] = v2[i] = i+1; //This should make both vectors equal {1,2,3} at the end of the loop
sum += v1[i]*v2[i]; //Component-wise, performing the dot product operation

std::cout<< sum <<std::endl;
return 0;

当代码运行完成后,输出应该是 1*1 +2*2 +3*3 = 14

但是,输出实际上是 647194768,这似乎没有任何意义。我从一些 friend 那里听说,在 C++ 中,如果你不小心初始化数组,就会发生一些疯狂的事情,但我完全傻眼了,这么简单的事情怎么会搞得这么糟糕。

您能否更深入地了解为什么会发生这种情况,C++ 的逻辑是什么导致了这种情况?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com