首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >正负FizzBuzz

正负FizzBuzz
EN

Code Review用户
提问于 2015-11-07 15:29:04
回答 1查看 481关注 0票数 3

我想消除我的Fizz类程序中的代码重复。有什么想法吗?

代码语言:javascript
复制
#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));
}
EN

回答 1

Code Review用户

发布于 2015-11-07 18:04:00

将通用代码移动到

函数

要消除重复,您可以做的第一件事是获取通用代码并将其移动到函数中。在您的例子中,结果如下:

代码语言:javascript
复制
// Returns 1 for buzz, 0 for any other.
int handleNum(int num)
{
    // if the number is multiple of both three and five
    if (num % 15 == 0) {
        printf("lancelot\n");
    }
    // if the number is multiple of 3
    else if(num % 3 == 0) {
        printf("Fizz\n");
    }
    // if the number is multiple of 5
    else if(num % 5 == 0) {
        printf("Buzz\n");
        return 1;
    }
    else {
        printf("%d\n", num);
    }
    return 0;
}

int myseries(int n) {
    int i, cpt = 0;
    if (n < 0) {
        for (i = 0; i >= n; i--) {
            cpt += handleNum(i);
        }
    }
    else {
        for (i = 0; i <= n; i++) {
            cpt += handleNum(i);
        }
    }
    return cpt;
}

处理阴性和阳性的

接下来你可以做的就是把消极的和积极的情况组合到同一个循环中。两个循环重复相同的次数,只是方向不同。因此,您可以只记住原始数字是否为负数,然后只在正方向上迭代,如下所示:

代码语言:javascript
复制
int myseries(int n) {
    int i, cpt = 0;
    int numberSign = (n < 0) ? -1 : 1;

    n *= numberSign;
    for (i = 0; i <= n; i++) {
        cpt += handleNum(i * numberSign);
    }
    return cpt;
}

其他事情

你的2级压痕对我的眼睛来说太小了。为了正确区分不同的等级,我不得不把压痕增加到4。

main()中打印结果时,还应该打印换行符。当我运行您的程序时,我的shell提示符放在输出的末尾。

票数 3
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/110109

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档