2016-09-14 100 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--]; 

    }