簡體   English   中英

在 C 中編寫一個程序,它將打印兩個不同系列數組中的偶數和奇數。 [號碼將由用戶插入]

[英]Write a program in C which will print the even numbers and the odd numbers in two different series of array. [Numbers will be inserted by users]

這是我被要求解決的問題 -> 所以我編寫了以下代碼 -> 我在 Windows 10 上使用 gcc 編譯器運行此代碼。

#include <stdio.h>
int main()
{
    int a, b[a], i;
    //The Max. range to print the odd and even numbers
    printf("Enter a range to print the odd and even numbers-->\n"); 
    scanf("%d", &a);
    for (i = 0; i < a; i++)
    {
        scanf("%d", &b[i]);
    }
    i--;
    for (i; i <= a; i--)
    {
        printf("The Even numbers are -->\n");
        if (b[i] % 2 == 0)
        {
            printf("%d", b[i]);
        }
        printf("The Odd numbers are -->\n");
        if (b[i] % 2 != 0)
        {
            printf("%d", b[i]);
        }
    }
    return 0;
}

但是,只執行了代碼的第一部分。 該程序既不從用戶[在數組中]獲取任何輸入,也不返回任何錯誤。 你能幫我讓'C'代碼工作嗎?

您不能使用a來設置數組b的大小,因為a沒有值。 只需在獲得a的值后聲明b

int a;
printf("Enter a number-->\n");
scanf("%d",&a);
int b[a];

此外,您還有一種非常奇怪的方式來遍歷您的數組。 什么反對這樣的事情:

printf("\nThe Even numbers are -->\n");
for(int i = 0; i<a;i++){
     if(b[i] %2 == 0)
         printf("%d ",b[i]);
}
printf("\nThe Odd numbers are -->\n");
for(int i = 0; i<a;i++){
     if(b[i] %2 != 0)
         printf("%d ",b[i]);
}

暫無
暫無

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

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