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. 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. If a worker works equal more than 3 years but less than 10 years, the salary increase 5% each year. And if a worker works equal or more than 10 years. The salary increase 8% each year.
For example, if you want to check the salary after 12 years. 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%.
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.