繁体   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