gpt4 book ai didi

C 输入的计数用逗号分隔

转载 作者:太空宇宙 更新时间:2023-11-04 05:36:36 24 4
gpt4 key购买 nike

我有一个代码可以检查数字是奇数还是偶数。我使用 char 输入并用逗号分隔每个数字。一切正常,但我需要计算输入了多少个数字,其中有多少是偶数。因为逗号,我撞墙了。我试图搜索谷歌,但我的英语不太好,我找不到这样的功能。也许我应该循环输入数字,直到用户只需按回车键即可开始检查偶数和奇数。到目前为止我的代码:

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);

关于C 输入的计数用逗号分隔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33377221/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com