2016-09-14 116 views
-3

我想将两个数组合并成一个。但不知道为什么数字出来而不是所需的数字,这个数字代表什么。为什么我得到这个数字?

#include<iostream> 
#include<conio.h> 

using namespace std; 

void MergeArray(int[], int, int[], int,int[]); 

void main() 
{ 
    int A[50], m, B[50], n, C[100],a, mn; 

    cout<<"Enter the size of First Array::\n"; 
    cin>>m; 
    cout<<"Enter the First Array(ASCENDING ORDER)\n"; 
    for(int i=0; i<m ; i++) 
     cin>>A[i]; 

    cout<<"Enter the size of Second Array::\n"; 
    cin>>n; 
    cout<<"Enter the Second Array(DESCENDING ORDER) ::\n"; 
    for(int j=0; j<n; j++) 
     cin>>B[j]; 

    mn=m+n; 
    MergeArray(A,m,B,n,C); 

    cout<<"The Array After merging is ::\n"; 
    for(int k=0; k < mn; k++) 
     cout<<C[k]<<"\n"; 
    cout<<"Press any key"; 
    cin>>a; 

} 


void MergeArray(int a[],int M , int b[], int N, int c[]) 
{ 
    int x,y,z; 
    z=0; 

    for(x=0, y=N-1; x<M && y>=0;) 
    { 
     if(a[x]<=b[y]) 
      c[z++]=a[x++]; 

     else if(b[y]<a[x]) 
      c[z++]=b[y--]; 
    } 

    if(x<M) 
    { 
     while(x<M) 
      c[z++]=a[x++]; 
    } 

    if(y>0) 
    { 
     while(y>=0) 
      c[z++]=b[y++]; 

    } 

    getch(); 

} 

Image of the output screen}

+0

对不起,我只是找到了正确的地方,我的问题 –

+0

不应该'如果(Y> 0)'是'如果(Y> = 0)','y ++'是'y - '? – Jeremy

回答

2

我觉得问题就在这里:

if(y>0) 
{ 
    while(y>=0) 
     c[z++]=b[y++]; // <-- y++ instead of y-- 

} 

你应该减少y,不增加它。

0

您看到这个奇怪的数字,因为您打印未初始化的数组项。 您不会在此处理第二个数组中的最后一个元素。你也使用增量为y,但你应该使用递减。 而不是

if(y>0) 
{ 
    while(y>=0) 
     c[z++]=b[y++]; 

} 

您应该使用

if(y>=0) 
    { 
     while(y>=0) 
      c[z++]=b[y--]; 

    }