如何读取直到EOF并打印输入的偶数/奇数?

我有下面的C代码,它读取用户输入直到文件末尾(ctrl + d)并将它们存储在一个数组中。 然后,它应该打印一行中的所有奇数,然后在另一行上打印偶数。 由于某种原因,它没有按预期工作。

当我输入以下内容时:

1 2 4 16 32 64 128 256 512 1024 2048 4096 the output is: Odd numbers were: Even numbers were: 2 16 64 256 1024 4096 Expected output: Odd numbers were: 1 Even numbers were: 2 4 16 32 64 128 256 512 1024 2048 4096 

代码如下:

 #include  int main(void){ int array[1000]; int i,j,k; int counter = 0; for(i=0; scanf("%d", &array[i]) != EOF; i++){ scanf("%d", &array[i]); counter = counter+1; } printf("Odd numbers were: "); for(j=0; j<counter; j++){ if(array[j]%2 != 0){ printf("%d ", array[j]); } } printf("\n"); printf("Even numbers were: "); for(k=0; k<counter ; k++){ if(array[k]%2 == 0){ printf("%d ", array[k]); } } printf("\n"); } 

您的问题有一个更简单的解决方案

希望你喜欢

 #include int main() { int num,od = 0, ev = 0; int odd[1000],even[1000]; while(scanf("%d",&num) == 1) { if(num%2==0) { even[ev] = num; ev++; } else { odd[od] = num; od++; } } printf("Odds numbers are: "); for(int i = 0;i 

程序输出与预期输出匹配

快乐的编码

好吧,你已经接受了一个完全不同的方法,但你的例子是不正确的,因为你在每个循环阶段做了一个scanf ,然后在for body中做了另一个,所以你在每个循环传递中做了两个 scanf ,这使得第二个要杀死数组元素i的第一个值。 这使您松开了一半的读取元素,并解释了您获得的输出。 只需将scanf放入循环体内即可使其正常工作。