Search code examples
coperatorscs50multiplicationpopulation

C stops woking when a vaiable is multiplied and divided with double digit numbers


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

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

    // TODO: Prompt for end size
    int e;
    do
    {
        e = get_int("End size : ");
    }
    while (e < s);

    // TODO: Calculate number of years until we reach threshold
    
    int n = s;
    int y = 0;
    while (n < e) 
    {
        n = n + n / 3 - n / 4 ;
        
        y++;
    }
    
    // TODO: Print number of years
    printf("Years: %i\n", y);

}

I am able to run the above code perfectly and get the desired results. However when i try to replace the n's calculation part by simplifying the math the code stops working i.e it does not calculate what its intended to calculate and keeps the program in the input taking mode i.e it lets you type in the terminal without giving output. I replaced the n's calculation part with n = (13 * n) / 12


Solution

  • Because of integer arithmetics, the expressions n = n + n / 3 - n / 4; and n = n * 13 / 12; are not equivalent: integer division rounds toward zero so for example the first expression increments n from 3 to 4 but not the second expression.

    You should use floating point arithmetics for this problem:

    #include <cs50.h>
    #include <stdio.h>
    
    int main(void) {
        // TODO: Prompt for start size
        int s;
        do {
            s = get_int("Start size: ");
        } while (s < 9);
    
        // TODO: Prompt for end size
        int e;
        do {
            e = get_int("End size: ");
        } while (e < s);
    
        // Calculate number of years until we reach threshold
        double n = s;
        int y = 0;
        while (n < e) {
            n = n * 13.0 / 12.0;
            y++;
        }
        
        // TODO: Print number of years
        printf("Years: %i\n", y);
        return 0;
    }