將n美分轉換成25、10、5和1美分的硬幣總共有多少種轉換方法?
運行結果如下:
25
13
如果n不在0~99之間,輸出提示資訊“the money is invalid!”
運行結果如下:
101
the money is invalid!
輸入格式:
整數,表示美分數
輸入可能不是[0,99]之間的整數。輸入不在該區間時,輸出為“the money is invalid!”。
輸出格式:
轉換方法數或者提示資訊“the money is invalid!”(不帶引號啊,單詞間只有一個空格)
解決方法:借助for回圈
#include<iostream>
using namespace std;
int main()
{
int n, i, j, t, num = 0;
int a[3]={25,10,5};
cin >> n;
if(n>99 || n<0)
cout << "the money is invalid";
else{
for(j=n/a[0];j>=0;j--) //j表示25美分的張數
{
int temp1 = n - j * a[0]; //temp1表示除去j張25美分后的剩余
for(t=temp1/a[1];t>=0;t--) //t表示10美分的張數
{
int temp2 = temp1 - t * a[1]; //除去j張25美分和t張10美分后的剩余
for(i=temp2/a[2];i>=0;i--) //i表示5美分的張數
{
num++; //num表示方法數
}
}
}
cout << num << endl;
}
return 0;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/64527.html
標籤:基礎類
上一篇:關于cmake的問題
