我想消除我的Fizz类程序中的代码重复。有什么想法吗?
#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));
}发布于 2015-11-07 18:04:00
函数
要消除重复,您可以做的第一件事是获取通用代码并将其移动到函数中。在您的例子中,结果如下:
// 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;
}接下来你可以做的就是把消极的和积极的情况组合到同一个循环中。两个循环重复相同的次数,只是方向不同。因此,您可以只记住原始数字是否为负数,然后只在正方向上迭代,如下所示:
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提示符放在输出的末尾。
https://codereview.stackexchange.com/questions/110109
复制相似问题