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

标签 c arrays

我正在尝试添加两个不同长度的数组(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/

相关文章:

c - GCC 没有重新排序堆栈变量

java - 数组类型困惑?

java - 读取jar文件中的目录

arrays - 剖析这段代码,解释 - 检查数组是否是另一个数组的子集

php - 我如何获取从一个页面到另一个重定向页面的数组ID

c++ - 计算一条线上的元素

c++ - 在特定场景中指针取消引用和强制转换之间的关系不明确

进程可以创建额外的 shell 可重定向文件描述符吗?

c++ - Linux中的UDP sendto是否会返回ENOBUFS?

c++ - 将一个字节组合成 long long