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

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

    // TODO: Prompt for end size
    float endSize;
    do
    {
        endSize = get_int("End Size: " );
    }
    while (endSize < startSize);

    // TODO: Calculate number of years until we reach threshold
    int years = 0;
    while (startSize < endSize)
    {
        startSize += (float) startSize / 12;
        years++;
    }
    // TODO: Print number of years
    printf("Years: %i\n", years);
}

These are the error I get:

:( rejects invalid populations and then handles population 9
    expected "Years: 8", not "Years: 9\n"
:( rejects invalid populations and then handles population 20
    expected "Years: 20", not "Years: 21\n"
:( handles starting population of 100
    expected "Years: 115", not "Years: 116\n"

It looks like I am getting an extra year. Please help?

1 Answer 1

0

Hmmm -- all the errors are "off by 1" errors. That's a clue.

Here is your main loop:

while (startSize < endSize)
{
    startSize += (float) startSize / 12;
    years++;
}

Question: What happens in the loop when startSize is exactly equal to endSize? Does it loop one more time? Should it? ;-)

It's all about exactly and correctly understanding the program spec.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • I tried changing the while condition to: while (startSize <= endSize); while (startSize <= endSize) { startSize += (float) startSize / 12; years++; } When I I tried test with the same startSize and endSize, I get Years = 1 which is suppose to be zero.
    – Ben
    Commented Apr 14, 2023 at 3:43

You must log in to answer this question.

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