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

标签 c++ arrays

<分区>

我昨天才开始尝试学习 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++ 的逻辑是什么导致了这种情况?

最佳答案

您不小心将 sum += 行放在了 for 循环之外。这是因为循环中没有大括号。所以只有第一行 v1[i]... 包含在 for 循环中。像这样改变它:

/*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

for(int i=0; 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;

请注意在 for 循环语句周围使用大括号 { .. } 。现在给出正确答案:14。

关于c++ - 数组未按 C++ 中的预期填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24580465/

相关文章:

c++ - 生成 C++ 构造函数的 Vim 宏

c++ - Eclipse C++ 未定义引用

c++ - 绑定(bind)返回值和可变参数模板

C++模板类实例问题

javascript - jQuery Post 不发布多维数组数据

java - 数组大小与java无关吗?

c - 释放结构数组

c++ - 为什么 Sleep(500) 花费超过 500 毫秒?

php - 将查询结果转换为关联数组

java - 在文件上使用扫描仪并保存在阵列上