为什么这个程序运行不出结果

#include<stdio.h>
int main()
{
int x;
int one, two, five;



scanf_s("%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 + two * 2 + five * 5 == x * 10)
            {//因为two 和five单位全是一角,所以要乘2或5,x*10是换算单位 {
                printf("可以用%d个一角,%d个两角和%d个五角凑%d元", one, two, five, x);
            }
                goto out;  //当凑满了金额就跳出所有循环体,目的是只要一个排列组合就够了
        }
    }    
}

out: //跳到此处,结束所有循环体
return 0;
}

把goto那行放到if中即可,因为如果是放到if后面,则只判断第一种情况就跳出了所有循环。

下面的代码在Dev-C++中测试,把scanf_s()改为了scanf()。

修改如下:


#include<stdio.h>
int main()
{
    int x;
    int one, two, five;
    
     
      
    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 + two * 2 + five * 5 == x * 10)
                {//因为two 和five单位全是一角,所以要乘2或5,x*10是换算单位 {
                    printf("可以用%d个一角,%d个两角和%d个五角凑%d元", one, two, five, x);
                    goto out;  //当凑满了金额就跳出所有循环体,目的是只要一个排列组合就够了
                }
                    
            }
        }    
    }
    out: //跳到此处,结束所有循环体
    return 0;
}

img

改动处见注释 “修改” ,goto out; 应括入if(){} 里,供参考:

#include<stdio.h>
int main()
{
    int x;
    int one, two, five;
    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 + two * 2 + five * 5 == x * 10)
                {//因为two 和five单位全是一角,所以要乘2或5,x*10是换算单位 {
                    printf("可以用%d个一角,%d个两角和%d个五角凑%d元", one, two, five, x);

                    goto out;
                }// 修改,goto 语句要括到if(){...; goto out}里面
            }
        }
    }
    out: printf("end"); //跳到此处,结束所有循环体
    return 0;
}

你n输入了多少?不是所有的n都有解