0

In lab activity of week0 of CS50X 2021, I have found this logical error. The system is so programmed by the university to expect output 2 for the following inputs but actually, it must be 1 because after one year the llama's population becomes 1191.466663. Give it looks and tells me if it's an error or I am thinking wrong.

**

ERROR:
expected "Years: 2", not "Years: 1\n"
Log
running ./population...
sending input 1100...
sending input 1192...
checking for output "Years: 2"...
Expected Output:
Years: 2
Actual Output:
Years: 1

** Here is my complete code:

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

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

    // TODO: Prompt for end size
    do
    {
        end_size = get_int("End size: ");
    }
    while (end_size < start_size);

    // TODO: Calculate number of years until we reach threshold


    float increment = start_size;
    int years = 0;
    //int round_increment = round(increment);
    do
    {
        increment = increment + increment / 12;
        //increment = floor(increment + 0.5);
        if (increment < end_size)
        {
            years ++;
        }
    }
    while (increment < end_size);

    // TODO: Print number of years
    printf("Years: %i\n", years);
}
2
  • Can you pleas put your code so that the error can be found
    – Vsjain
    Commented Jan 5, 2021 at 4:12
  • Actually, I am not pointing out errors in my code. I want to point out the logical error in a university program that is meant to check student's code. Commented Jan 5, 2021 at 8:22

2 Answers 2

1

The check50 result is correct because the spec says "Your program should then calculate the (integer) number of years required for the population to reach at least the size of the end value."

One problem with the code is increment declared as float. It is bound to cause errors of rounding. Declare it an int and let division handle the truncating.

Another problem is the do/while loop. The if conditional causes year to be undercounted, because it will not increment on the last iteration. But since the do will execute at least once, removing the conditional will cause year to be 1 when start == end.

One possible solution is change the do/while to a simple while and remove the conditional.

0

Also the mathematical formula you used is wrong, you should write increment = increment + ( increment / 3 ) - ( increment / 4 );

1
  • increment / 3 - increment / 4 = 4increment -3increment / 12 = increment / 12 . So, I hope now you can understand ( if you know basic algebra ), this mathematical formula is correct. Commented Jan 16, 2021 at 5:33

You must log in to answer this question.

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