簡體   English   中英

編寫C程序以將數組中的數字排列為一系列奇數和偶數

[英]Write a C program to arrange the numbers in an array as a series of odd and even numbers

我已經嘗試創建上面的程序,但是有一些錯誤。這是我的程序

#include <stdio.h>
#include <conio.h>

void main()
{
    int a[20],o[20],e[20],c[40],i,j,k,l,n;
    printf("enter size of array");
    scanf("%d",&n);
    printf("enter array");
    for(i=1;i<=n;i++)
    {
        scanf("%d",&a[i]);
    }
    for(i=1;i<=n;i++)
    {
        for(j=1;j<=n;j++)
        {
            for(k=1;k<=(n-j);k++)
            {
                if(a[i]%2==0)
                {
                    o[j]=a[i];
                    break;
                }
        else
        {
            e[k]=a[i];
        }
        }
        }
    }
    for(i=1;i<=j;i++)
    {
        c[l]=o[i];
    }
    for(i=1;i<=k;i++)
    {
        c[l+k]=e[k];
    }
    printf("The new array is");
    for(l=1;l<=(j+k);l++)
    {
        printf(" %d ",c[l]);
    }
    getch();
}

有人可以幫我糾正上述程序中的錯誤嗎?有人可以給我一些如何成為一名優秀C程序員的提示嗎?

問題可能是因為您從未初始化變量l 使用未初始化的變量會產生未定義的行為 (google that)。

同樣,您的數組索引從1開始,例如在這里:

for (i = 1; i <= n; i++)

在C數組中,索引從0開始,因此您應該這樣寫:

for (i = 0; i < n; i++)

這適用於所有其他for循環。

  • 但是可能還有其他問題。
  • 您的程序看起來過於復雜
  • 使用odd而不是oeven而不是e等變量名將使程序更易於閱讀。
  • 您的程序格式不正確。 正確的格式對於可讀性至關重要

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM