長さが異なる2つの配列(arr1[6]
とarr2[9]
)を追加しようとしています。私は次のように>>これまでにされたライトすることができたコードCで長さの異なる2つの配列の合計を求めるプログラミング
#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]);
}
}
}
例えばIは入力要素の数と2つの配列の要素:
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
Iを得ます次の結果:
10
14
4
11
2
14
7864429
50397191
3
結果が期待される結果
若干異なっています誰かが私に間違っていることを教えてもらえますか?
P.S.スペルミスや文法エラーがある場合はお詫び申し上げます。あなたが言うあなたの例では
c配列の値に定数を指定して試してみてください。 –
Cで変数を宣言すると、ほとんどの場合、変数を初期化するまでは迷惑データが含まれています。配列のすべての要素を0にするには、次のように宣言します。 'int arr [5] = {};' –
@RayHamel - それを実行したことは、皆さんの助けに感謝します。再度、感謝します。 – m3itself