如何在两个数组中添加元素,但顺序相反
How to the add elements in two arrays, but in reverse order?
此代码的目的是添加两个数组中的元素,但顺序相反我不明白我为什么不编译(语法、循环或数组错误??)。你能给我指正确的方向吗?非常感谢。
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
const int ARRAY1_LEN = 3;
const int ARRAY2_LEN = 2;
int MyInts1[ARRAY1_LEN] = { 35, -3, 0};
int MyInts2[ARRAY2_LEN] = {20, -1};
cout << "Multiplying each int in MyInt1 by each in MyInts2 ... But Backwards:" << endl;
for(int Array1Index = 0; Array1Index < ARRAY1_LEN - 1; Array1Index--);
for(int Array2Index = 0; Array2Index < ARRAY2_LEN -1; Array2Index--);
cout << MyInts1[Array1Index] << " x " << MyInts2[ Array2Index ] << " = " << MyInts1[Array1Index] * MyInts2[Array2Index] << endl;
return 0;
}
您的逻辑不正确。您从索引0
开始,然后返回。这意味着,您正在进入负范围(-1,-2,-3,…),并且每个负数都满足循环条件。
它应该是:
int main()
{
const int ARRAY1_LEN = 3;
const int ARRAY2_LEN = 2;
int MyInts1[ARRAY1_LEN] = { 35, -3, 0 };
int MyInts2[ARRAY2_LEN] = { 20, -1 };
cout << "Multiplying each int in MyInt1 by each in MyInts2 ... But Backwards:" << endl;
int start_1 = ARRAY1_LEN > 0 ? ARRAY1_LEN - 1 : 0;
int start_2 = ARRAY2_LEN > 0 ? ARRAY2_LEN - 1 : 0;
for(int Array1Index = start_1; Array1Index >= 0; Array1Index--)
{
for(int Array2Index = start_2; Array2Index >= 0; Array2Index--)
{
cout << MyInts1[Array1Index] << " x " << MyInts2[ Array2Index ] << " = " << MyInts1[Array1Index] * MyInts2[Array2Index] << endl;
}
}
return 0;
}
如果至少有一个数组为空,则此代码也将正常工作。
哦,还有一件事:你的代码也是完全错误的,因为你在for
后面有分号(;
),这意味着每个循环都有一个空的主体。所以,即使你的for
是正确的,你也不会看到任何东西。
程序中有两个错误:
- 整个循环体仅由for循环后的分号组成,而不是您实际希望在循环中运行的代码。这也解释了代码不编译的原因:乘法不是循环体的一部分,因此循环头中定义的
Array1Index
和Array2Index
不再存在 - 尽管您正在减少arry索引,但您仍然从0开始,因此您将访问负数组索引
所以你的代码实际上应该是这样的:
for (int Array1Index = ARRAY1_LEN - 1 ; Array1Index >= 0; Array1Index--){
for (int Array2Index = ARRAY2_LEN - 1; Array2Index >=0; Array2Index--){
cout << MyInts1[Array1Index] << " x " << MyInts2[Array2Index] << " = " << MyInts1[Array1Index] * MyInts2[Array2Index] << endl;
}
}
相关文章:
- 使用std::transform将一个范围的元素添加到另一个范围中
- 如何将元素添加到数组的线程安全函数?
- 如何将元素添加到向量的字符串位置
- 将数组的元素添加到链表中
- 如何在C++中将元素添加到非固定大小的数组中?
- 如何使用模板根据类型将元素添加到各种容器中
- 将在堆栈上声明的元素添加到静态数组
- 有什么方法可以将元素添加到列表中,如图所示?
- 继承层次结构并将元素添加到向量
- gStreamer 将元素添加到通过 gst_parse_launch 创建的管道中
- 将新元素添加到列表中,并返回对该元素的引用?
- 将元素添加到 std::list 在多线程中,无需 C++ 互斥锁
- C++如何通过超出大小将元素添加到指针数组中
- 将集合的随机元素添加到列表中,然后将其从原始集合中移除
- 将字符串集合中的元素添加到字符串集合的向量中
- 为什么 memcpy() 是一种将元素添加到 'std::map' 的方法?
- 如何有条件地将元素添加到 std::array - C++11
- 如何在 c++ 中将元素添加到数组的最后一个
- 如何使用<<运算符将元素添加到向量?
- 将元素添加到结构向量的全球向量中