我想添加兩個長度不同的數組(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.如果有拼寫錯誤或語法錯誤,我很抱歉。
嘗試用一個常量給c數組的值賦值,看看會發生什麼。 –
當你在C中聲明一個變量時,在大多數情況下,它包含垃圾數據,直到你初始化爲止 - 這包括數組元素在分配給它們之前。要使數組0中的每個元素都聲明爲:int arr [5] = {};' –
@RayHamel - 那個人做到了,我感謝大家的幫助,尤其是你的幫助。再次感謝。 – m3itself