合并数组的程序打印0而不是实际的合并数组 [英] Program to merge arrays prints 0s instead of the actual merged array
问题描述
将两个数组合并为一个单独的第三个数组的程序实际上并没有执行任何操作,尽管我经过了几次代码。尝试更改循环计数器,变量,似乎没有任何效果。因此,在我输入了数组的大小和元素之后,由于某种原因,合并后的数组只是一串零。
这里是代码:
#include iostream
#使用命名空间std定义MAX 100
;
int main()
{
int a [MAX],n1,i;
int b [MAX],n2,j;
int r [MAX],k;
cout<< 数组1:;
cout<< \n输入数组中的元素数:;
cin>> n1;
cout<< 输入数组的元素:; (i = 0; i <n1; i ++)的
{
cin> a [i];
}
cout<< \nArray 2:;
cout<< \n输入数组中的元素数:;
cin>> n2;
cout<< 输入数组的元素:; (j = 0; j <n2; j ++)的
{
cin> b [j];
}
//合并数组
,而(i< n1&& j< n2)
{
if(a [i]< b [j])
{
r [k] = a [i];
i ++;
k ++;
}
else
{
r [k] = b [j];
j ++;
k ++;
}
}
而(i {
r [k] = a [i];
i ++;
k ++;
}
而(j {
r [k] = b [j];
j ++;
k ++;
}
cout<< \n合并数组:\n; (k = 0; k
{
cout<< r [k]<< ;
}
返回0;
}
for(i = 0; i {
cin> a [i];
}
和
<$ p对于(j = 0; j< n2; j ++),$ p>
b [j];
}
以 i
结尾和 j
设置为 n1
和 n2
。
您可能希望将它们重新初始化为 0
,然后继续。
在while循环之前添加 i = 0; j = 0; k = 0;
会有所帮助。
为什么需要初始化变量?
如果未初始化,k将包含可能不等于 0 $ c $的垃圾值c>。
对于除 0
之外的任何其他值,您的代码将无法达到预期的效果。
Program to merge two arrays into a separate third array doesn't actually do anything, despite me going through the code a couple times. Tried changing loop counters, variables, nothing seems to work. So, after I input the array sizes and elements, the merged array is just a string of zeroes for some reason.
Here's the code:
#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];
}
and
for (j=0;j<n2;j++)
{
cin >> b[j];
}
end with i
and j
set to n1
and n2
.
You may want to reinitialize them to 0
and then proceed.
Adding i=0;j=0;k=0;
before the while loop will help.
Why do you need to initialize variables?
If not initialized, k will contain junk values which may not be equal to 0
.
For any value other than 0
your code will not behave the way you expect.
这篇关于合并数组的程序打印0而不是实际的合并数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!