2016-11-29 18 views
2

我想添加兩個長度不同的數組(arr1[6]arr2[9])。我已經能夠寫到目前爲止如下:>>代碼在C編程中查找兩個長度不同的數組的總和

#include <stdio.h> 
#include <stdlib.h> 
#define maxElements 100 

int main() 
{ 
    int n1,n2,arr1[maxElements],arr2[maxElements],i,temp,c[maxElements]; 

    // number of elements of the array 1 

    printf("How many elements will the array 1 have \n"); 
    scanf(" %d",&n1); 

    // number of elements of the array 2 

     printf("How many elements will the array 2 have \n"); 
      scanf(" %d",&n2); 

    // taking the elements of array 1 

    printf("Enter the elements of array 1\n"); 

    for(i=0;i<n1;i++) 
    { 
     scanf(" %d",&arr1[i]); 
    } 

    // taking the elements of array 2 

    printf("Enter the elements of array 2\n"); 

    for(i=0;i<n2;i++) 
    { 
     scanf(" %d",&arr2[i]); 
    } 

    // adding the elements of array 1 and array 2 

    if(n1>=n2) 
    { 
     for(i=0;i<n1;i++) 
     { 

      c[i]=arr1[i]+arr2[i]; 
     } 
    } 
    else 
    { 
     for(i=0;i<n2;i++) 
     { 
      c[i]=arr1[i]+arr2[i]; 

     } 
    } 

    //print the output 

    printf("The output of addition of 2 arrays is\n"); 

if(n1>=n2) 
    { 
     for(i=0;i<n1;i++) 
     { 
      printf("%d\n",c[i]); 
     } 
    } 
    else 
    { 
     for(i=0;i<n2;i++) 
     { 
      printf("%d\n",c[i]); 
     } 
    } 

} 

當我輸入元件的數量和兩個數組的元素,例如:我

How many elements will the array 1 have: 
6 

How many elements will the array 2 have: 
9 

Enter the elements of array 1: 
3 5 2 7 1 8 

Enter the elements of array 2: 
7 9 2 4 1 6 8 5 3 

得到以下結果:

10 
14 
4 
11 
2 
14 
7864429 
50397191 
3 

結果與預期的結果

略有不同

有人能告訴我我做錯了什麼?

P.S.如果有拼寫錯誤或語法錯誤,我很抱歉。

+0

嘗試用一個常量給c數組的值賦值,看看會發生什麼。 –

+0

當你在C中聲明一個變量時,在大多數情況下,它包含垃圾數據,直到你初始化爲止 - 這包括數組元素在分配給它們之前。要使數組0中的每個元素都聲明爲:int arr [5] = {};' –

+0

@RayHamel - 那個人做到了,我感謝大家的幫助,尤其是你的幫助。再次感謝。 – m3itself

回答

0

在您的例子,你說:

if(n1>=n2) 
    { 
    for(i=0;i<n1;i++) 
    { 

     c[i]=arr1[i]+arr2[i]; 
    } 
    } 

一旦i會高於6(的n2值),它試圖在arr2訪問的元素不存在;因此它只是返回隨機數字,而不像你期望的那樣。

可以將所有元素初始化爲0,或者查看向量。

+0

或者,一旦達到'n1','n2'中的較小值,只使用較長數組中的值。 –

+0

在你的例子中,arr1有9個元素。 – jamnin

+0

在你的例子中,arr1有6個元素,arr2有9個元素。當您嘗試將arr1的第7個元素添加到arr2時,就是發生問題時。這是因爲第7個元素沒有價值。 – jamnin

1

如果將數組填充超過極限,這是錯誤的。就像你的arr1具有存儲6個元素的能力,但是你要將arr1 [6]中的值填充到arr1 [8]。你可能會出現腐敗錯誤。對於你的邏輯,如果n1小於n2,那麼只運行循環直到n1。因此,arr2和arr1會自行增加,直到循環到達n1,arr2的其餘部分將保持原樣。所以你不會得到奇怪的輸出。

0

它正在訪問不存在的元素。

for(i = 0 ; i < min(n1, n2); i++){ 
     c[i] = arr1[i] + arr2[i]; 
} 
相關問題