Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/64.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C buzzfizz程序中的代码重复,包括负数_C - Fatal编程技术网

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

C buzzfizz程序中的代码重复,包括负数,c,C,您好,我想避免程序中的代码重复(buzzfizz包括负数) #包括 intmyseries(intn){ int i,cpt=0; if(n=n;i--){ //如果数字是3和5的倍数 如果(i%15==0){ printf(“lancelot\n”); } //如果数字是3的倍数 如果(i%3==0),则为else{ printf(“Fizz\n”); } //如果数字是5的倍数 else如果(i%5==0){ printf(“Buzz\n”); cpt++; } 否则{ printf(“%d

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

#包括
intmyseries(intn){
int i,cpt=0;
if(n<0){
对于(i=0;i>=n;i--){
//如果数字是3和5的倍数
如果(i%15==0){
printf(“lancelot\n”);
}
//如果数字是3的倍数
如果(i%3==0),则为else{
printf(“Fizz\n”);
}
//如果数字是5的倍数
else如果(i%5==0){
printf(“Buzz\n”);
cpt++;
}
否则{
printf(“%d\n”,i);
}
}
返回cpt;
}
否则{

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

将常用代码提取到函数中。请去掉不必要的空行。谢谢,但如果我不想添加其他函数……也许最好继续问。@HajarM出于好奇,为什么不添加其他函数?
#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));
}