buzzfizz程序中的代码重复,包括负数

时间:2015-11-07 15:00:52

标签: c

您好我想避免程序中的代码重复(buzzfizz包括负数)

#include <stdio.h>

int myseries(int n) {
  int i, cpt = 0;
  if (n < 0) {
    for (i = 0; i >= n; i--) {
      // if the number is multiple of both three and five
      if (i % 15 == 0) {
        printf("lancelot\n");
      }
      // if the number is multiple of 3
      else if(i % 3 == 0) {
        printf("Fizz\n");
      }
      // if the number is multiple of 5
      else if(i % 5 == 0) {
        printf("Buzz\n");
        cpt++;
      }
      else {
        printf("%d\n", i);
      }
    }
    return cpt;
  }
  else {
    for (i = 0; i <= n; i++) {
      // if the number is multiple of both three and five
      if (i % 15 == 0) {
        printf("lancelot\n");
      }
      // if the number is multiple of 3
      else if(i % 3 == 0) {
        printf("Fizz\n");
      }
      //if the number is multiple of 5
      else if(i % 5 == 0) {
        printf("Buzz\n");
        cpt++;
      }
      else {
        printf("%d\n",i);
      }
    }
    return cpt;
  }
}

//example

main() {
  printf("the number of buzz is : %d", myseries(-16));
}

1 个答案:

答案 0 :(得分:3)

您可以使用n的绝对值(即abs(n))作为i的上限,并记录n的符号(即{{1}输出。