简体   繁体   English

输入的 C 计数以逗号分隔

[英]C count numbers entered separated by commas

I have a code that checks if number is odd or even.我有一个代码可以检查数字是奇数还是偶数。 I use char to input and separate each number with commas.我使用 char 输入并用逗号分隔每个数字。 Everything works great, but I need to count how many numbers have been entered and how many of them are even numbers.一切都很好,但我需要计算输入了多少数字,其中有多少是偶数。 I ran into a wall because of commas.我因为逗号撞到了墙上。 I tried to search google, but my english is not so good and I can't find such function.我试图搜索谷歌,但我的英语不太好,我找不到这样的功能。 Maybe I should loop number entries until user simply press enter to start checking even numbers and odd numbers.也许我应该循环输入数字,直到用户只需按 Enter 键开始检查偶数和奇数。 My code so far:到目前为止我的代码:

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, ",");
    }

If we use variable++ that means increment value of variable by 1.如果我们使用 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);

As mentioned in the comments, as you read in each number count the total number of values read in. Then when you do the check for an even number, increments another counter for that:正如评论中提到的,当您读取每个数字时,计算读取的值的总数。然后,当您检查偶数时,会为此增加另一个计数器:

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