簡體   English   中英

查找C中N個案例之間的偶數

[英]Find even numbers between N number of cases in C

我想編寫一個代碼,如果您找到N個個案(y)之間的所有偶數。 接下來的y行將包含一個數字(1 <= n1 <= 100)。 對於每一行,我想找到它們之間的偶數。 因此,例如:

input:
2 (number of cases; 1<=y<=10)
1
7
Output:
No even numbers
2 4 6

如果它們之間沒有偶數,則打印“無偶數”,例如:

所以我到目前為止所做的是:

#include <stdio.h>
int main()
{
    int n1, n2, i, j, p, y;
    printf("number of intervals: ");
    scanf("%d", &y);
    for(j=1; j<=y; j++)
    {
        scanf("%d", &n1);
        for(i=1;i<=n1; i++)
        {
            p=i%2;
            if(p==0)
                printf(" %d", i);     
        }
        return 0;
    } 
}

事實是,我不知道如何對代碼實現間隔數,它只能在兩個間隔下工作。

如果您想用不同的值做類似的事情,創建函數總是一個好主意。您可以創建一個函數並根據需要多次調用該函數。

void printInterval(int n1, int n2){  //function will print all even 
    for(i=n1;i<=n2; i++)//number between n1 and n2 (both inclusive)
    {
        p=i%2;
        if(p==0)
        printf(" %d", i);   

    }
}

暫無
暫無

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

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