C语言,合并数组,只有前八位正确。求解

C语言,合并数组,只有前八位正确。求解

#include<stdio.h>
int main()
{
    int a[100],b[50],c[150];
    int n,m,i,f,t,e,k,s,x;
    int j=0;
    f=t=0;
    scanf("%d",&n);
    for(i=0;i<n;i=i+1)
    {scanf("%d",&a[i]);}
    scanf("%d",&m);
    for(x=0;x<m;x=x+1)
    {scanf("%d",&b[x]);}
       while(f<n&&t<m)
      {
        if(a[f]>b[t])
         {c[j]=b[t];
         t=t+1;
         j=j+1;
    
        }
        else if (a[f]<b[t])
        {
            c[j]=a[f];
            f=f+1;
            j=j+1;
    
        }
        printf("%d\n",c[j-1]);
    }
    printf("%d\n",j);
    printf("%d\n",t);
    printf("%d\n",f);
    if(f<n)
        {for(f;f<n;f=f+1)
            c[j]=a[f];
            j=j+1;
        }
    else
        {for(t;t<m;t=t+1)
            c[j]=b[t];
        j=j+1;
            
        }
        printf("%d\n",a[8]);
            for(i=0;i<n+m;i=i+1)
                printf("%d ",c[i]);
    return 0;
}

这段代码的问题在于,在循环合并数组时,没有正确地使用while循环判断条件。导致合并时只能正确输出前8个元素,而后面的元素无法正确合并。

应该将合并循环中的printf语句放在if块外面,同时将while的判断条件修改为f<n && t<m,具体修改方法如下:

while(f<n && t<m)
{
    if(a[f]>b[t])
    {
        c[j]=b[t];
        t=t+1;
        j=j+1;
    }
    else if (a[f]<b[t])
    {
        c[j]=a[f];
        f=f+1;
        j=j+1;
    }
    else
    {
        c[j]=a[f];
        f=f+1;
        t=t+1;
        j=j+1;
    }
}


此外,还需要注意一些细节问题,例如:

1 在else分支中缺少else语句块,可能会导致某些情况下出现意外的错误。

2 在for循环中,如果没有对变量i进行预先初始化,可能会导致一些奇怪的错误,最好对其进行初始化。

最终修复后的代码片段如下所示:

#include<stdio.h>

int main()
{
    int a[100], b[50], c[150];
    int n, m, i, f, t, e, k, s, x;
    int j = 0;
    f = t = 0;
    
    scanf("%d", &n);
    for(i = 0; i < n; i++)
    {
        scanf("%d", &a[i]);
    }
    
    scanf("%d",&m);
    for(x = 0; x < m; x++)
    {
        scanf("%d", &b[x]);
    }
    
    while(f < n && t < m)
    {
        if(a[f] > b[t])
        {
            c[j] = b[t];
            t = t + 1;
            j = j + 1;
        }
        else if (a[f] < b[t])
        {
            c[j] = a[f];
            f = f + 1;
            j = j + 1;
        }
        else
        {
            c[j] = a[f];
            f = f + 1;
            t = t + 1;
            j = j + 1;
        }
    }
    
    if(f < n)
    {
        for(f;f<n;f=f+1)
        {
            c[j]=a[f];
            j=j+1;
        }
    }
    else
    {
        for(t;t<m;t=t+1)
        {
            c[j]=b[t];
            j=j+1;
        }
    }
    
    printf("%d\n",a[8]);
    for(i = 0; i < n + m; i++)
    {
        printf("%d ", c[i]);
    }
    printf("\n");
    
    return 0;
}