合并数组的程序打印 0 而不是实际合并的数组

Program to merge arrays prints 0s instead of the actual merged array

本文关键字:数组 合并 程序 打印      更新时间:2023-10-16

将两个数组合并为单独的第三个数组的程序实际上并没有做任何事情,尽管我浏览了几次代码。尝试更改循环计数器,变量,似乎没有任何效果。因此,在我输入数组大小和元素后,由于某种原因,合并的数组只是一串零。

代码如下:

#include "iostream"
#define MAX 100
using namespace std;
int main()
{
int a[MAX],n1,i;
int b[MAX],n2,j;
int r[MAX],k;
cout << "Array 1: ";
cout << "nEnter number of elements in the array: ";
cin >> n1;
cout << "Enter the elements of the array: ";
for (i=0;i<n1;i++)
{
cin >> a[i];
}
cout << "nArray 2: ";
cout << "nEnter the number of elements in the array: ";
cin >> n2;
cout << "Enter the elements of the array: ";
for (j=0;j<n2;j++)
{
cin >> b[j];
}
//Merging the arrays
while (i < n1 && j < n2)
{
if (a[i] < b[j])
{
r[k] = a[i];
i++;
k++;
}
else
{
r[k] = b[j];
j++;
k++;
}
}
while (i < n1)
{
r[k] = a[i];
i++;
k++;
}
while (j < n2)
{
r[k] = b[j];
j++;
k++;
}
cout << "nMerged Array: n";
for (k=0;k<n1+n2;k++)
{
cout << r[k] << " ";
}
return 0;
}
for (i=0;i<n1;i++)
{
cin >> a[i];
}

for (j=0;j<n2;j++)
{
cin >> b[j];
}

i结尾,j设置为n1n2

您可能需要重新初始化它们以0然后继续。

在 while 循环之前添加i=0;j=0;k=0;会有所帮助。

为什么需要初始化变量?

如果未初始化,k 将包含可能不等于0的垃圾值。

对于除0以外的任何值,代码的行为方式将不按预期方式运行。