如何在两个数组中添加元素,但顺序相反

How to the add elements in two arrays, but in reverse order?

本文关键字:元素 添加 顺序 数组 两个      更新时间:2023-10-16

此代码的目的是添加两个数组中的元素,但顺序相反我不明白我为什么不编译(语法、循环或数组错误??)。你能给我指正确的方向吗?非常感谢。

#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是正确的,你也不会看到任何东西。

程序中有两个错误:

  1. 整个循环体仅由for循环后的分号组成,而不是您实际希望在循环中运行的代码。这也解释了代码不编译的原因:乘法不是循环体的一部分,因此循环头中定义的Array1IndexArray2Index不再存在
  2. 尽管您正在减少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;
    }
}