给你若干钱, 有1元, 5元, 10元, 25元, 50元这5种小钱可以换. 求共有多少种方法.
#include <iostream> |
using namespace std; |
int s( int a) |
{ |
switch (a) |
{ |
case 1: return 1; break ; |
case 2: return 5; break ; |
case 3: return 10; break ; |
case 4: return 25; break ; |
case 5: return 50; break ; |
} |
} |
int way( int j, int k = 5) |
{ |
int s( int a); |
if (j == 0) |
return 1; |
else if ((j < 0)||(k == 0)) |
return 0; |
else |
return way(j, k - 1) + way(j - s(k), k); |
} |
int main() |
{ int p; |
int way( int j, int k =5); |
cout << "请输入钱数:" ; |
cin >> p; |
cout << way(p, 5); |
} |
要是想一一列出1元, 5元, 10元, 25元, 50元各换了多少张, 再写一个程序.
#include <iostream> |
using namespace std; |
//1,5,10,25,50 |
int main() |
{ |
int a, i, j, k, o, p,q = 0; |
cin >> a; |
for (i = 0; i <= ( int )a/50; i++) |
{ for (j = 0; j <= ( int )(a - 50*i)/25; j++) |
{ for (k = 0; k <= ( int )(a-50*i-j*25)/10; k++) |
{ for (o = 0; o <= ( int )(a-50*i-j*25-k*10)/5; o++) |
{ for (p = 0; p <= ( int )(a-50*i-j*25-k*10-o*5); p++) |
{ |
if (50*i+25*j+10*k+5*o+p == a) |
{ |
q++; |
cout << "50的换" <<i<< "张,25的换" <<j<< "张,10的换" <<k<< "张,5的换" <<o<< "张,1块的换" <<p<< "张." <<endl; |
}}}}}} |
cout<< "共有:" <<q<< "种方法." <<endl; |
} |