The loop should calculate the count of years which the town need to see its population greater or equal to currentPopulation inhabitants.
int "initialPopulation" The population at the beginning of a year.
double "percent" The percentage of growth per year.
int "visitors" The visitors (new inhabitants per year) who come to live in the town.
int "currentPopulation" The population at present.
So I am trying to return the count of years, however the loop only loops one time no matter what the difference between InitialPopulation and CurrentPopulation is, and I want it too loop until it reaches CurrentPopulation.
That would be my problem, tested the logic on textbook and it should really go through, so either my logic is broke or I don't understand some kind of While loop rule.
Please comment, if I was not too clear on my description. Thank you in advance.
public static int GetYears(int initialPopulation, double percent, int visitors, int currentPopulation)
{
if (initialPopulation <= 0 || visitors < 0 || currentPopulation <= 0 || currentPopulation < initialPopulation)
{
throw new ArgumentException(null);
}
else if (percent < 0 || percent > 100)
{
throw new ArgumentOutOfRangeException(nameof(percent));
}
else
{
int countOfYear = 0;
while (initialPopulation < currentPopulation)
{
int surplus = ((int)(initialPopulation * percent) + visitors) - initialPopulation;
initialPopulation += surplus;
countOfYear++;
}
return countOfYear;
}
}
}
Your logic to calculate surplus is wrong. You don't need to subtract initial population. Also, divide percent by 100.
public static int GetYears(int initialPopulation, double percent, int visitors, int currentPopulation)
{
if (initialPopulation <= 0 || visitors < 0 || currentPopulation <= 0 || currentPopulation < initialPopulation)
{
throw new ArgumentException(null);
}
else if (percent < 0 || percent > 100)
{
throw new ArgumentOutOfRangeException(nameof(percent));
}
else
{
int countOfYear = 0;
while (initialPopulation < currentPopulation)
{
int surplus= (int)(initialPopulation * percent / 100 + visitors);
initialPopulation += surplus;
countOfYear++;
}
return countOfYear;
}
}