如何计算输入文件中的数字倍数?

时间:2010-05-02 18:49:36

标签: c

我试图从用户输入文件中计算出2,3和6的倍数。但出于某种原因,我的柜台不起作用。我可以请任何小伙伴。 我的代码:

#include <stdio.h>
int main (void)
{
  int num[12];
  int i;
  int counttwo;
  int countthree;
  int countsix;
  int total=0;
  printf("enter 12 integer numbers:\n");
  for(i=0;i<12;i++){

 scanf("%d", &num[i]);
  }
  for(i=0;i<12;i++){
    counttwo=0;
      if(num[i]%2==0){
       counttwo++;
      }
      countthree=0;
       if(num[i]%3==0)
  {
      countthree++;
   }
       countsix=0;
      if(num[i]%6==0)
        {
          countsix++;
}
      printf("There are %d multiples of 2:\n", counttwo);
      printf("There are %d multiples of 3:\n", countthree);
      printf("There are %d multiples of 6:\n", countsix);
}
  return 0;

}

3 个答案:

答案 0 :(得分:1)

每次迭代步骤都会重置计数器变量。把

counttwo=0;
countthree=0;
countsix=0;

for()之前的代码。

答案 1 :(得分:1)

考虑第二个循环中counttwocountthreecountsix的值会发生什么变化。请特别注意行counttwo = 0countthree = 0countsix = 0

答案 2 :(得分:0)

  • counttwo
  • 之前将countthreecountsixfor-loop重置为0
  • 删除for-loop
  • 的多余scanf
  • 将3 printf移出for-loop

这是固定代码

#include <stdio.h>
int main (void)
{
  int num[12];
  int i;
  int counttwo = 0; //Reset counttwo, countthree, and countsix to 0
  int countthree = 0;
  int countsix = 0;
  int total=0;
  printf("enter 12 integer numbers:\n");

  for(i=0;i<12;i++){

      scanf("%d", &num[i]);

      if(num[i]%2==0){
       counttwo++;
      }

      if(num[i]%3==0){
       countthree++;
      }

      if(num[i]%6==0) {
        countsix++;
      }
  }

  printf("There are %d multiples of 2:\n", counttwo);
  printf("There are %d multiples of 3:\n", countthree);
  printf("There are %d multiples of 6:\n", countsix);

  return 0;

}