簡體   English   中英

輸入的 C 計數以逗號分隔

[英]C count numbers entered separated by commas

我有一個代碼可以檢查數字是奇數還是偶數。 我使用 char 輸入並用逗號分隔每個數字。 一切都很好,但我需要計算輸入了多少數字,其中有多少是偶數。 我因為逗號撞到了牆上。 我試圖搜索谷歌,但我的英語不太好,我找不到這樣的功能。 也許我應該循環輸入數字,直到用戶只需按 Enter 鍵開始檢查偶數和奇數。 到目前為止我的代碼:

char str[256];
 fgets (str, 256, stdin);
    char *pt;
    pt = strtok (str,",");
    while (pt != NULL) {
        int a = atoi(pt);

        if (a%2 == 0)
        {
            printf("Number is even\n");

        }
        else
        {
            printf("Number is odd!\n\n");
        }
        printf("%d\n", a);
        pt = strtok (NULL, ",");
    }

如果我們使用 variable++,這意味着變量的值增加 1。

char str[256];
fgets (str, 256, stdin);
char *pt;
int odd_count = 0,even_count = 0;
pt = strtok (str,",");
while (pt != NULL) {
    int a = atoi(pt);

    if (a%2 == 0)
    {
        printf("Number is even\n");
        even_count++;
    }
    else
    {
        printf("Number is odd!\n\n");
        odd_count++;
    }
    printf("%d\n", a);
    pt = strtok (NULL, ",");
}
printf("Count of even numbers in the sequence is %d",even_count);
printf("Count of odd numbers in the sequence is %d",odd_count);
printf("Total numbers in the sequence is are %d",even_count + odd_count);

正如評論中提到的,當您讀取每個數字時,計算讀取的值的總數。然后,當您檢查偶數時,會為此增加另一個計數器:

int countTotal = 0, countEven = 0;
while (pt != NULL) {
    int a = atoi(pt);

    countTotal++;
    if (a%2 == 0)
    {
        printf("Number is even\n");
        countEven++;
    }
    else
    {
        printf("Number is odd!\n\n");
    }
    printf("%d\n", a);
    pt = strtok (NULL, ",");
}

暫無
暫無

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

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