0

I've made the following code which is supposed to calculate the number of years it takes to reach a goal population assuming the population grows by 1/3 every year and 1/4 dies, as required in the lab 1 directions. my calculation of adding 1/12 every year doesn't work for some reason i.e after correctly compiling and requesting start size and goal size, the cursor moves down a row and doesn't display the result

#include <cs50.h>
#include <stdio.h>

int main(void)
{
// TODO: Prompt for start size
int start;
    do
    {
       start = get_int("Enter start size: ");
    }
    while(start < 9);

// TODO: Prompt for end size
int goal;
    do
    {
       goal = get_int("Enter goal population size: ");
    }
    while (goal < start);
// TODO: Calculate number of years until we reach threshold
int years = 0;
    while (start < goal)
    {
        start += (start / 12);
        years++;
    }
// TODO: Print number of years
    printf("Years: %i\n", years);

}

1 Answer 1

1

In C, integer division truncates. Any start value less than 12 will result in an infinite loop. Keeping truncation in mind, with start value 9, start += start / 12 evaluates to 9 because start / 12 evaluates to 0. Do the born/dies calculations separately.

3
  • Thankyou so much!!! Mar 15, 2023 at 12:59
  • Do you know why it worked for the instructor on the supersection video. he did += start / 12 Mar 15, 2023 at 13:05
  • It "worked" in the video with input of 12, which is greater than 9. Mar 16, 2023 at 10:24

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .