Population growth math issue in c

190 Views Asked by At

I have looked this over and am wondering where my math issue is. I believe that it should be calculating correctly, but the floats do not round up, .75 to 1 to add to the count for births/deaths. I am a novice to c. Here is the code I have so far:

float births(long popul);
float deaths(long pop);
long yearAdjustment(long pop);
int threshold(long population, long end);

int main(void){

    long begin = 0;
    long end = 0;
    int year = 0;
    float input = 0.0;

    do{
        // TODO: Prompt for start size
       input = get_float("Beginning population: ");
       begin = (long) roundf(input);
    } while (begin < 9);

    do{
        // TODO: Prompt for end size
        input = get_float("Ending population: ");
        end = (long) roundf(input);
    } while (end < begin || end <= 0);

    if(begin == end)
    {
        year = 0;
    } else
    {
        year = threshold(begin, end);
    }
    // TODO: Print number of years
    printf("Years: %i\n", year);
}

    
float births(long pop){
    float tmp = pop / 3;
    return tmp;
}

float deaths(long pop){
     float tmp = pop / 4;
     return tmp;
}

long yearAdjustment(long pop){
    long tmp = pop + ((long) roundf(births(pop) - deaths(pop)));
    return tmp;
}

int threshold(long population, long end){
    int years = 0;
    long tmp = 0;

    // TODO: Calculate number of years until we reach threshold
    while (tmp < end){
        tmp += yearAdjustment(population);
        years++;
    }
    return years;
}

I'm using longs because the numbers may start in the thousands. The floats are for a little precision, more rounding, in the divisions in births/deaths. Essentially it should increment by roughly 1/10/100... respectively of single/tens/hundreds... input. 1.25 on an input of 9. That is where the decimal is important. Technically every 4 years I gain 1 extra. Say 18 as an end should be 8 years.

Thank you.

2

There are 2 best solutions below

0
On

Initialize tmp with the population and remove the population added in year adjustment. Population is being added each iteration, creating growth beyond the year adjustment. Similar to balancing a checking account, you wouldn't add the original balance to each transaction.

1
On

The main problem is that you are using 'long', that is the same as 'long int', so it will not give you any precision in your divisions. You can use 'long double' instead, this way it will also give you the decimals.