C++ Variables not updating in loop

Viewed 476

For some reason the values in the loop do not update. Instead of taking the new values they are assigned in the loop they stay the same as when first assigned. Why is this?


using namespace std;

int main() {

    int town_A_Pop;
    int town_A_Growth;
    int town_B_Pop;
    int town_B_Growth;
    int years = 0;

    cout << "Enter the polulation of town A and of town B:" << endl;
    cin >> town_A_Pop >> town_B_Pop;
    cout << "Enter the growth rate of town A and of town B:" << endl;
    cin >> town_A_Growth >> town_B_Growth;

    do {
      town_A_Pop = town_A_Pop * (1 + (town_A_Growth / 100));
      cout << town_A_Pop << endl;
      town_B_Pop = town_B_Pop * (1 + (town_B_Growth / 100));
      cout << town_B_Pop << endl;
      years++;
    }
    while (town_A_Pop < town_B_pop);

    cout << "It took " << years << " years for Town A to overtake Town B." << endl;
    cout << "Town A Population: " << town_A_Pop << endl;
    cout << "Town B Population: " << town_B_Pop << endl;

    return 0;
}


2 Answers

I assume that town_A_Pop and town_B_Pop don't update.

If town_A_Growth is less than 100(and greater or same than 0) then (town_A_Growth / 100) will evaluate to 0 and (1 + (town_A_Growth / 100)) will evaluate to 1.

In that case, town_A_Pop = town_A_Pop * 1 so it will stay same. Same goes to town_B_Pop.

To fix the problem, you can change variables into float or double, or multiply first then divide by 100 like below:

do {
    town_A_Pop = (town_A_Pop * (100 + town_A_Growth)) / 100;
    cout << town_A_Pop << endl;
    town_B_Pop = (town_B_Pop * (100 + town_B_Growth)) / 100;
    cout << town_B_Pop << endl;
    years++;
}
while (town_A_Pop < town_B_pop);

It will still won't get bigger if both population and growth are too small, though.

Your problem is Type Variables Error

int town_A_Pop;
int town_A_Growth;
int town_B_Pop;
int town_B_Growth;
int years = 0;

change to

double town_A_Pop;
double town_A_Growth;
double town_B_Pop;
double town_B_Growth;
double years;

This should be ok. Because if using int to do division it not able return decimal number. Like:

int tmp = 1;
int division = tmp / 5; //This result will return 0 , not return 0.2 
Related