算法练习4
* 题目*:
A man has a rather old car being worth 2000. He saw a secondhand car being worth 8000. He wants to keep his old car until he can buy the secondhand one.
He thinks he can save $1000 each month but the prices of his old car and of the new one decrease of 1.5 percent per month. Furthermore the percent of loss increases by a fixed 0.5 percent at the end of every two months.
Example of percents lost per month:
If, for example, at the end of first month the percent of loss is 1, end of second month percent of loss is 1.5, end of third month still 1.5, end of 4th month 2 and so on …
Can you help him? Our man finds it difficult to make all these calculations.
How many months will it take him to save up enough money to buy the car he wants, and how much money will he have left over?
typedef struct 和struct :
typedef struct Student
{
int a;
}Stu;
在c++里面, typedef是别名的意思,Stu是Student的别名,定义 Stu test 即可
struct Student
{
int a;
}stu1;//stu1是一个变量
typedef struct Student2
{
int a;
}stu2;//stu2是一个结构体类型=struct Student
vector应用:
(1)头文件#include.
(2)创建vector对象,vector vec;
(3)尾部插入数字:vec.push_back(a);
(4)使用下标访问元素,
cout<<vec[0]<<endl
;记住下标是从0开始的。
(5)使用迭代器访问元素.
vector<int>::iterator it;
for(it=vec.begin();it!=vec.end();it++)
cout<<*it<<endl;
(6)插入元素: vec.insert(vec.begin()+i,a);在第i+1个元素前面插入a;
(7)删除元素: vec.erase(vec.begin()+2);删除第3个元素vec.erase(vec.begin()+i,vec.end()+j);删除区间[i,j-1];区间从0开始
(8)向量大小:vec.size();
(9)清空:vec.clear();
取整函数:
需要头文件
#include<cmath>
1. ceil() 向上取整
2. floor()向下取整
3. round()四舍五入
代码:
#include<vector>
#include<iostream>
using namespace std;
class BuyCar
{
public:
static std::vector<int> nbMonths(int startPriceOld, int startPriceNew, int savingperMonth, double percentLossByMonth)
{
int waiteMonth = 1;
int savingSum = 0;
double nowPriceNew = startPriceNew;
double nowPriceOld=startPriceOld;
while (1)//run of time
{
if (waiteMonth%2==0)//increasing 0.5 percent per two months
{
percentLossByMonth += 0.5;
//cout << "percentLossByMonth=" << percentLossByMonth << endl;
}
if ((savingSum + nowPriceOld) >= nowPriceNew)
{
int leaveOut =round( savingSum + nowPriceOld - nowPriceNew);
return {waiteMonth-1, leaveOut };
}
waiteMonth++;// a month is gone
nowPriceOld -= nowPriceOld*percentLossByMonth*0.01;
nowPriceNew -= nowPriceNew*percentLossByMonth*0.01;
savingSum += savingperMonth;
}
};
};
int main()
{
vector<int> test = BuyCar::nbMonths(12000, 8000, 1000, 1.5);
cout << test[0]<<" "<<test[1] << endl;
}