比较元素两边元素的总和' N'在一个数组(尝试2)

时间:2017-07-25 22:32:52

标签: c++ arrays

我考虑了收到的提示,我应用了一些模块化思维,然后再次尝试。该程序运行。根据我硬连接到数组元素的值集合,我接收索引,其中左边的元素总和等于右边元素的总和。我理解这是演习的目的。

我选择不在本练习中使用向量,因为我需要练习来记住数组有一个指向位置1的常量指针,因此,当数组传递给函数时,必须记住也传递数组的大小,或者,在传递数组的函数内部,可以循环遍历数组并计算其中的元素数,然后使用count作为数组大小。

请批评我的新功能代码,并指出我做错的其他事情。 谢谢。

#include "stdafx.h"
#include <iostream>
using namespace std;

/***************************************
* RIGHT SIDE OF ARRAY
* Calculates sum of elements right of n
***************************************/
int rightSideOfArray(int arrayOne[], int size, int i)
{
    int n = 0;

    //loop through array and get right hand sum
    for (int j = 1 + i; j < size; j++)
    {

        n += arrayOne[j];

    }
    return n;


}


/***************************************
* LEFT SIDE OF ARRAY
* Calculates sum of elements left of n
***************************************/
int leftSideOfArray(int arrayOne[], int size, int i)
{
    int n2 = 0;

    //find left hand sum
    for (int j = i - 1; j >= 0; j--)
    {
        n2 += arrayOne[j];

    }
    return n2;

}



int main()
{
    //define and declare array
    int const SIZE = 7;
    int arrayOne[SIZE] =
    { 1,2,3,4,3,2,1 };
    int n = 0;
    int n2 = 0;
    int count = 0;

    //do comparison
    for (int i = 0; i < SIZE; i++)
    {

    //compare right hand and left hand side and return right values
    if (rightSideOfArray(arrayOne, SIZE, i) == 
    leftSideOfArray(arrayOne,       SIZE, i))

     counter++;
    cout << i << endl;

}
    if (counter == 0)

    cout << -1 << endl;

system("PAUSE");

return 0;

}

旧代码:第一次尝试 我读过同一个查询的先前解决方案,但我无法弄清楚出错的地方。我理解的挑战是循环遍历整数数组,在每个元素&#39; i&#39;,我必须将所有元素添加到&#39; i&#39;得到左边的总和&#39;然后我必须将所有元素添加到&#39; i&#39;得到右手总和&#39;。之后,我应该比较阵列右手边和左手边的总和。 如果两个总和相等,我应该让我的函数返回右手和左手均衡发生的指数。否则,我应该返回-1。

任何人都可以告诉我为什么我只得到&#39; -1&#39;作为我的回答?

int equalSidesOfAnArray(int arrayOne[], int n, int n2)
{

    //loop through array and get right hand sum
    for (int i = 0; i < sizeof(arrayOne); i++)
    {

        for (int j = 1 + i; j < sizeof(arrayOne); j++)
        {
            n += arrayOne[j];
            n2 += arrayOne[j - 1];
        }

        if (n == n2)
            return arrayOne[i];
        else
            return -1;

    }

}

int main()
{
    // define and declare array
    int const SIZE = 7;
    int arrayOne[SIZE] = { 1, 2, 3, 4, 3, 2, 1 };
    int n = 0;
    int n2 = 0;


    int answer = equalSidesOfAnArray(arrayOne, n, n2);
    cout << answer << endl;


    system("PAUSE");

    return 0;

}

1 个答案:

答案 0 :(得分:0)

首先,作为函数参数的arrayOne是指向数组第一个元素的指针,sizeof(arrayOne)是此指针的大小,而不是SIZE的大小sizeof(arrayOne)你的阵列 即使在main()中,SIZE * sizeof(int)也会返回n

当您使用C ++编码时,请使用std::vector / std::array并消除C数组。这样可以省去这些麻烦和much more

考虑初始化n2-1的位置(您不需要将其作为参数传递),并返回{{1}}。