![](/img/trans.png)
[英]Why am I not getting the right output for this implementation of nth Fibo Number?
[英]why i am getting this number?
我正在嘗試將兩個數組合並為一個。 但無法弄清楚為什么會出現數字而不是所需的數字以及這個數字意味着什么。
#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();
}
我認為問題就在這里:
if(y>0)
{
while(y>=0)
c[z++]=b[y++]; // <-- y++ instead of y--
}
你應該減少y
,而不是增加它。
您看到這個奇怪的數字是因為您打印了數組的未初始化項。 此處不處理第二個數組中的最后一個元素。 您也對y
使用增量,但您應該使用減量。 代替
if(y>0)
{
while(y>=0)
c[z++]=b[y++];
}
你應該使用
if(y>=0)
{
while(y>=0)
c[z++]=b[y--];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.