C buzzfizz程序中的代码重复,包括负数
您好,我想避免程序中的代码重复(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
#包括
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));
}