实验4-2-4 换硬币 (20分)
程序员文章站
2022-06-07 15:14:13
...
解一:
#include<stdio.h>
int main(void){
int money,five,two,one,count=0,total;
scanf("%d",&money);
for(five=money/5;five>0;five--)
for(two=money/2;two>0;two--){
if(five*5+two*2<money){ //通过这个判断条件便可保证至少有一枚一分的硬币
total=money-five*5-two*2+five+two; //统计硬币枚数
printf("fen5:%d, fen2:%d, fen1:%d, total:%d\n",five,two,money-five*5-two*2,total);
count++; //统计换发个数
}
}
printf("count = %d\n",count);
return 0;
}
解二:
#include<stdio.h>
int main(void){
int five,two,one,count,x;
count=0;
scanf("%d",&x);
for(five=x/5;five>=1;five--){
for(two=x/2;two>=1;two--){
for(one=x;one>=1;one--){
if(one+two*2+five*5==x){
count=count+1;
printf("fen5:%d, fen2:%d, fen1:%d, total:%d\n",five,two,one,five+two+one);
}}}}
printf("count = %d\n",count);
return 0;
}
解二和解一思路上是一致的,但解二用了三个for循环,
时间复杂度更大,所以解二的效率比解一低。
下一篇: linux自定义命令
推荐阅读