简体   繁体   中英

Code duplication in buzzfizz program including negative numbers

Hello i want to avoid code duplication in my program (buzzfizz including negative numbers)

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

您可以使用n的绝对值(即abs(n) )作为i的上限,并记录n的符号(即bool sgn = ( n > 0 ) ? 1 : 0; )作为输出。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM