gpt4 book ai didi

c - 在 C 编程中求两个长度不同的数组之和

转载 作者:太空宇宙 更新时间:2023-11-03 23:42:56 24 4
gpt4 key购买 nike

我正在尝试添加两个不同长度的数组(arr1[6]arr2[9])。目前我能写的代码如下>>

#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

结果与预期结果略有不同

10 14 4 11 2 14 8 5 3

有人能告诉我我做错了什么吗?

P.S. I apologise if there are any spelling mistakes or grammar errors.

最佳答案

如果你填充数组超过它的限制是错误的。就像你的 arr1 有存储 6 个元素的能力,但你要在 arr1[6] 到 arr1[8] 中填充值。您可能会收到损坏错误。对于您的逻辑,如果 n1 小于 n2,则只运行循环直到 n1。因此 arr2 和 arr1 将增加自身,直到循环到达 n1 并且 arr2 的剩余部分将完好无损。所以你不会得到奇怪的输出。

关于c - 在 C 编程中求两个长度不同的数组之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40856427/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com