2017-07-25 48 views
-2

我考慮到了收到的提示,我應用了一些模塊化思維,然後再次嘗試。程序運行。根據硬連接到數組元素的值的集合,我接收到作爲輸出的索引,其中左側元素的總和等於右側元素的總和。我理解這是演習的目標。比較數組中元素'N'兩邊元素的總和(嘗試2)

我在本練習中選擇不使用矢量,因爲我需要練習記住一個數組有一個常量指向位置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; 

} 

舊代碼:第一次嘗試 我看了以前的解決了這個相同的查詢,但我想不出哪裏出了問題。我所理解的挑戰是循環遍歷整數數組,在每個元素'i'處,我必須將所有元素添加到'i'的左側以獲得'左側總和'。然後,我必須將所有元素添加到'我'的右邊以獲得'右手總和'。之後,我應該比較我陣列的右側和左側的總和。 如果兩個和都相等,我應該讓我的函數返回發生右手和左手均衡的索引。否則,我應該返回-1。

有誰能告訴我爲什麼我只得到'-1'作爲我的答案?

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

'sizeof(arrayOne)'是指針的大小。不太可能是OP的設計目標。 – chux

+0

'cout << answer << endl;'無效C – chux

+0

即使如此,我正在使用C++, – Kate

回答

0

首先,arrayOne作爲函數的參數是一個指向數組的第一元素,和sizeof(arrayOne)是該指針的大小,而不是尺寸的陣列的SIZE
即使在main()中,sizeof(arrayOne)也會返回SIZE * sizeof(int)。當您在C++中編碼時,請使用std::vector/std::array並刪除C數組。這節省你這樣的麻煩和much more

並考慮您正在初始化的位置nn2(您不需要將其作爲參數傳遞),並返回-1

+0

謝謝你,我會在那裏開始....是的,我在這個新的可笑。 – Kate