[英]how do i add all the given conditions into one or two loops?
so I was given this problem to do at home and instructed to only use loops.所以我被要求在家里解决这个问题,并指示我只使用循环。
Write a method double calcFutureSalary(double curretSalary, int year) that takes an initial salary of a person, a number of year.编写一个方法 double calcFutureSalary(double curretSalary, int year) 获取一个人的初始薪水,年份数。 The method will calculate the salary after a certain number of years.该方法将在一定年限后计算工资。 If a worker works less than 3 years, the salary increase 3% each year.如果工人工作不到 3 年,工资每年增加 3%。 If a worker works equal more than 3 years but less than 10 years, the salary increase 5% each year.如果工人工作超过3年但不到10年,工资每年增加5%。 And if a worker works equal or more than 10 years.如果工人工作等于或超过 10 年。 The salary increase 8% each year.工资每年增长8%。
For example, if you want to check the salary after 12 years.例如,如果您想查看 12 年后的工资。 The first 2 year the salary will be increased by 3%, then for year 3 to year 9, the salary increase 5%, and for year 10 to year 12, the salary increase 8%.前 2 年加薪 3%,第 3 年到第 9 年加薪 5%,第 10 年到第 12 年加薪 8%。
The thing is, I only know how to do a part of it.问题是,我只知道如何做其中的一部分。 for example:例如:
for(int i = 1; i <= year; i++) {
currentSalary *= 1.03;
}
return currentSalary;
my Problem is I don't know how to apply the other conditions using loops afterwards.我的问题是我不知道之后如何使用循环来应用其他条件。 HELP PLEASE.请帮忙。
for(int i = 1; i <= year && i<=2 ; i++) {
currentSalary *= 1.03;
}
for (int i=3 ; i<= year && i<=9 ; i++)
And so on...
return currentSalary;
You can also make it less prone to bugs by not repeating yourself.您还可以通过不重复自己来减少错误的发生。
int i = 1;
for(; i <= year && i<=2 ; i++) {
currentSalary *= 1.03;
}
for (; i<= year && i<=9 ; i++)
And so on...
return currentSalary;
You can also use one single loop like this:您也可以像这样使用一个循环:
const int numIntervals = 3;
const int yearIntervals[] = {1,3,10,10000};
const float factors[] = {1.03f,1.05f,1.08f};
for ( int interval = 0 ; interval < numIntervals ; interval++ )
{
for ( int y = yearIntervals[interval]; y < yearIntervals[interval+1] && y<=year; y++ )
{
currentSalary *= factors[interval];
}
}
return currentSalary;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.