1

正在从 ACM 编程竞赛档案中搜索并找到椰子程序的解决方案:它有一个 goto,我该如何消除它?是否有模板或程序可以遵循。谢谢

/*
1997 East-Central ACM regional programming contest
Held on November 8, 1997
Coconuts, Revisited -- Problem 3
Sample solution by Ed Karrels, Ed@tool.com
November 1997
*/
#include <stdio.h>
/* return 1 if this number of coconuts can be divided up
properly between this number of people */
int SplitCoco(long n_coco, long n_people) {
long i;
for (i=0; i<n_people; i++) {
/* check that the coconuts divide by the number of people
plus one remainder */
    if (n_coco % n_people != 1) return 0;
    /* remove 1 for the monkey, and one person's share */
        n_coco = n_coco - 1 - (n_coco / n_people);
    }
    /* check that the remaining coconuts divide evenly among
    the people */
    return (n_coco % n_people) == 0;
}


int main() {
    long n_coco;
    long n_people;
    long i, j, k;

    FILE *inf = stdin;
    while (fscanf(inf, "%ld", &n_coco), n_coco!=-1) {
    /* starting at the # of coconuts-1, count down until
    a number of people is found that works */
        for (n_people=n_coco-1; n_people > 1; n_people--) {
            if (SplitCoco(n_coco, n_people)) {
                 printf("%ld coconuts, %ld people and 1 monkey\n",
                 n_coco, n_people);
                 goto found;
                 /* OK, so yea, I put a 'goto' in my code :-)
                it was quick and it works. I don't do
                it often, I swear. */
            }
        }
     /* if no number of people greater than 1 works, there is
     no solution */
        printf("%ld coconuts, no solution\n", n_coco);
        found:
    }
    return 0;
}
4

3 回答 3

8

在您的情况下,您可以制定一个单独的例程来计算whilegoto foundreturn.

通常,您可以将每个 goto 替换为一个标志和一些 while 循环。这不会使代码更易于阅读。

于 2012-09-09T16:49:42.837 回答
4

代替

goto found;

 break;

代替

 printf("%ld coconuts, no solution\n", n_coco);

和:

if(n_people <= 1)
    printf("%ld coconuts, no solution\n", n_coco);
于 2012-09-09T16:57:06.360 回答
1

另一个答案已经暗示了这一点,但也暗示它的可读性较低——我不同意——我发现它读起来就像它的意思。无论喜欢与否,它都值得作为一种可能的解决方案进行说明。

我的解决方案需要一个布尔类型的定义。我假设了 C99<stdbool.h>定义(或 C++ 编译)

这只是外部 while 循环的主体:

    bool found = false ;
    for (n_people=n_coco-1; n_people > 1 && !found; n_people--) 
    {
        found = SplitCoco(n_coco, n_people)
        if( found ) 
        {
            printf("%ld coconuts, %ld people and 1 monkey\n", n_coco, n_people);
        }
    }

    if( !found ) 
    {
        /* if no number of people greater than 1 works, there is no solution */
        printf("%ld coconuts, no solution\n", n_coco);
    }

在某些情况下,额外的每循环测试可能会令人望而却步,但我建议在大多数情况下它是微不足道的。

于 2012-09-09T17:25:16.357 回答