PTA---换硬币 (20 分)
生活随笔
收集整理的這篇文章主要介紹了
PTA---换硬币 (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 = 4AC: 題目要求按5分,2分1分的順序輸出,那么我們在計算的時候肯定優先把5分硬幣最多,然后是2分硬幣多一些,當確定了5分硬幣和2分硬幣之后,1分硬幣的數量也就確定了。
#include<stdio.h>int main() {int x;int five = 0;int two = 0;int one = 0;int total = 0;int cnt = 0;scanf("%d",&x);for(five = (x - 3) / 5;five > 0; five--)//這是5分錢{for(two = (x - 5 * five - 1) / 2 ;two > 0; two--)//2分錢{one = x - 5 * five - 2 * two;total = five + two + one;printf("fen5:%d, fen2:%d, fen1:%d, total:%d\n",five,two,one,total);cnt++;}}printf("count = %d",cnt);return 0; }?下面這個比較直白,但是復雜度比較高。
#include<stdio.h>int main() {int n;scanf("%d",&n);int five=0,two=0,one=0,i=0;int total=0,count=0;for(five=n/5;five>=0;five--){for(two=(n-five*5)/2;two>=0;two--){for(one=n-five*5-two*2;one>=0;one--){if((five*5+two*2+one)==n&&five>=1&&two>=1&&one>=1){total=five+two+one;printf("fen5:%d, fen2:%d, fen1:%d, total:%d\n",five,two,one,total);count++;}}}}printf("count = %d\n",count);return 0; }總結
以上是生活随笔為你收集整理的PTA---换硬币 (20 分)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JavaScript 身份证格式验证
- 下一篇: 东小店南少:让你终身收益的三个营销思维,