合并数组的程序打印 0 而不是实际合并的数组
Program to merge arrays prints 0s instead of the actual merged array
将两个数组合并为单独的第三个数组的程序实际上并没有做任何事情,尽管我浏览了几次代码。尝试更改循环计数器,变量,似乎没有任何效果。因此,在我输入数组大小和元素后,由于某种原因,合并的数组只是一串零。
代码如下:
#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
设置为n1
和n2
。
您可能需要重新初始化它们以0
然后继续。
在 while 循环之前添加i=0;j=0;k=0;
会有所帮助。
为什么需要初始化变量?
如果未初始化,k 将包含可能不等于0
的垃圾值。
对于除0
以外的任何值,代码的行为方式将不按预期方式运行。
相关文章:
- 合并排序不排序自创建数组类 c++
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- 我如何根据 c++ 中的行合并两个 2D 数组
- 使用基于数组的列表 c++ 合并 2 个数组
- 如何在 char 数组中合并两个数组以通过网络发送
- 合并数组的程序打印 0 而不是实际合并的数组
- 如果数组长度为 100000,则使用合并排序对反转进行计数会给出负数
- 合并两个数组后数组大小不正确
- 如何修复合并两个C++数组时'Invalid Pointer'
- 在OpenMP上的并行合并排序上的数组大小问题.如何将合并分类分类为更多任务
- C++全局常量数组:是否保证合并(优化)到一个副本中
- C - 为什么合并函数在递归调用后会逆转数组
- 合并排序 - 返回新数组,而不是将合并的数组复制到输入数组
- C MPI:STD ::在数组上合并
- 合并排序问题,在方法之间传递数组
- C 合并的数组输出错误
- 我如何在INT数组上实现合并排序
- C++将2个已排序的数组合并为1个已排序数组
- 将排序代码与数组合并,陷入合并,只需要一点点修正
- 将字符* 数组合并到uint16_t