c语言换硬币

7-69 换硬币 (20分)
将一笔零钱换成5分、2分和1分的硬币,要求每种硬币至少有一枚,有几种不同的换法?

输入格式:
输入在一行中给出待换的零钱数额x∈(8,100)。

输出格式:
要求按5分、2分和1分硬币的数量依次从大到小的顺序,输出各种换法。每行输出一种换法,格式为:“fen5:5分硬币数量, fen2:2分硬币数量, fen1:1分硬币数量, total:硬币总数量”。最后一行输出“count = 换法个数”。

输入样例:

13

输出样例:

fen5:2, fen2:1, fen1:1, total:4
fen5:1, fen2:3, fen1:2, total:6
fen5:1, fen2:2, fen1:4, total:7
fen5:1, fen2:1, fen1:6, total:8
count = 4

#include <stdio.h>
int main()
{
    int x;
    int count=0;
    int five,two,one;
    scanf("%d",&x);

    for(five=x/5;five>0;five--){
        for(two=x/2;two>0;two--){
            for(one=x;one>0;one--){
                if(five*5+two*2+one ==x){
                printf("fen5:%d, fen2:%d, fen1:%d, total:%d\n",five,two,one,five+two+one);
                count++;}
            }
        }
    }
    printf("count = %d\n",count);
    
    return 0;
}

运行结果如下:

13
fen5:2, fen2:1, fen1:1, total:4
fen5:1, fen2:3, fen1:2, total:6
fen5:1, fen2:2, fen1:4, total:7
fen5:1, fen2:1, fen1:6, total:8
count = 4

关键之处在于三种硬币要以从大到小的方式输出,显然5分硬币最多有x/5个,两分硬币最多有x/2个,一分硬币最多有x个,所以这里要注意。

其实通常我们比较常见的是按从小到大的顺序输出,只需要稍作改变。

#include <stdio.h>
int main()
{
    int x;
    int count=0;
    int five,two,one;
    scanf("%d",&x);

    for(five=1;five<=x/5;five++){
        for(two=1;two<=x/2;two++){
            for(one=1;one<=x;one++){
                if(five*5+two*2+one ==x){
                printf("fen5:%d, fen2:%d, fen1:%d, total:%d\n",five,two,one,five+two+one);
                count++;}
            }
        }
    }
    printf("count = %d\n",count);
    
    return 0;
}

运行结果如下:

13
fen5:1, fen2:1, fen1:6, total:8
fen5:1, fen2:2, fen1:4, total:7
fen5:1, fen2:3, fen1:2, total:6
fen5:2, fen2:1, fen1:1, total:4
count = 4

猜你喜欢

转载自blog.csdn.net/weixin_46530492/article/details/105728027