I've been given a problem to calculate the number of years(nbYear) it would take for a population(p0) to rise or decrease to a certain number of people(p) if the population would increas/decrease by precentage(percent) and additional people(aug) a year.
public static int nbYear(int p0, double percent, int aug, int p) {
int nbYear = 0;
while(p0 < p){
p0 = p0 + (p0 * percent) + aug;
nbYear = nbYear + 1;
}
return nbYear;
}
}
This code would be ok but I get a possible lossy conversion from double to int error. My question is how can you calculate a mathematical equation with mixed data types in (this case int and double) without any information loss?
Any help is much appreciated!
You cannot assign a double
value to an int
variable without explicitly handling the data loss. One way to do this is to explicitly use a narrowing cast to int
, under the assumption that a population cannot increase by a part of a person:
p0 = p0 + (int)(p0 * percent) + aug;
// Here --^