您好我想避免程序中的代码重复(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));
}
答案 0 :(得分:3)
您可以使用n
的绝对值(即abs(n)
)作为i
的上限,并记录n
的符号(即{{1}输出。