跳出多重循环

跳出多重循环

示例——用1角、2角、5角凑出一个预设的以元为单位的金额(要求整数元)

#include 
int main()
{
    int x;
    int one, two, five;
    printf("请输入需要的金额:");
    scanf("%d", &x);
    for (one = 1; one < x * 10; one++)
    {
        for (two = 1; two < x * 10 / 2; two++)
        {
            for (five = 1; five < x * 10 / 5; five++)
            {
                if (one * 1 + two * 2 + five * 5 == x * 10)
                {
                    printf("可以使用%d个1角+%d个2角+%d个5角得到%d元\n", one, two, five, x);
                }
            }
        }
    }

    return 0;
}

输入想要的金额(元)后,以上程序会输出所有组合。在实际应用中,如果我们只需要一个组合结果的话,可以在程序中加入代码,跳出多重循环

  • 方法一
    接力break (注意:break和continue只针对它所在的这个循环,单纯加上一条break只能跳出当前循环,回到上一级循环)
#include 
int main()
{
    int x;
    int exit = 0;
    int one, two, five;
    printf("请输入需要的金额:");
    scanf("%d", &x);
    for (one = 1; one < x * 10; one++)
    {
        for (two = 1; two < x * 10 / 2; two++)
        {
            for (five = 1; five < x * 10 / 5; five++)
            {
                if (one * 1 + two * 2 + five * 5 == x * 10)
                {
                    printf("可以使用%d个1角+%d个2角+%d个5角得到%d元\n", one, two, five, x);
                    exit = 1;
                    break;
                }
            }
            if (exit == 1)
                break;
        }
        if (exit == 1)
            break;
    }

    return 0;
}

因为break只是跳出当前循环,所以加上一个变量exit,配合if判断跳出外面的两重循环。

  • 方法二 goto
#include 
int main()
{
    int x;
    int one, two, five;
    printf("请输入需要的金额:");
    scanf("%d", &x);
    for (one = 1; one < x * 10; one++)
    {
        for (two = 1; two < x * 10 / 2; two++)
        {
            for (five = 1; five < x * 10 / 5; five++)
            {
                if (one * 1 + two * 2 + five * 5 == x * 10)
                {
                    printf("可以使用%d个1角+%d个2角+%d个5角得到%d元\n", one, two, five, x);
                    goto end;
                }
            }
        }
    }
end:
    return 0;
}

格式goto 标号,这个标号可以自定义,注意格式和放置的位置。
goto使用要谨慎,因为有观点任务goto破坏了程序的结构。但在这种情况下,即在循环最内层跳出的时候很管用。

你可能感兴趣的:(C语言编程,算法,c语言)