我有一个代码可以检查数字是奇数还是偶数。我使用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, ",");
}
答案 0 :(得分:3)
如果我们使用变量++,那意味着将变量的值增加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);
答案 1 :(得分:3)
正如评论中所提到的,当您在每个数字中读取时,读取的值总数。然后当您检查偶数时,为此增加另一个计数器:
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, ",");
}