I have been scratching my head over an issue in my loop for a homework assignment. I was asked to write a program which accepted input from user for population size and growth rate for two towns, and output how many years it would take for the two populations to become equal.
Everything has compiled fine, and the loop outputs appropriately for comparisons of small population sizes, but any input size of more than four digits and I start seeing very large negative numbers being output.
I initially tested with the following values: PopA input to 100, RateA input to .10, PopB input to 200, RateB input to .00, and that worked fine. However changing input populations to 1000 and 2000 gave me a very large negative value for PopA. I've tried changing the data types of the variables involved, but nothing has resolved the issue yet. Any assistance/suggestions you could offer would be much appreciated. Code is below. Compiled/written in CodeBlocks on Windows 10.
#include <iostream>
usingnamespace std;
int main()
{
int PopA;
int PopB;
int years = 0;
double RateA;
double RateB;
cout << "Please input current population for town A: ";
cin >> PopA;
cout << "Please enter the yearly rate of growth for town A: ";
cin >> RateA;
cout << "Please input current population for town B: ";
cin >> PopB;
cout << "Please enter the yearly rate of growth for town B: ";
cin >> RateB;
cout << endl;
do
{
years++;
PopA = (PopA * RateA) + PopA;
PopB = (PopB * RateB) + PopB;
cout << "The current population of town A is: " << PopA << " people." << endl;
cout << "The current population of town B is: " << PopB << " people." << endl;
cout << "Increase has been compared for " << years << " years." << endl;
cout << endl;
}while (PopA != PopB);
if (PopA == PopB)
{
cout << "The populations of both towns are equal." << endl;
cout << "Town A: " << PopA << " people." << endl;
cout << "Town B: " << PopB << " people." << endl;
cout << "Equivalence achieved in " << years << " years." << endl;
cout << endl;
}
return 0;
}
Thanks for the assistance! Adjusting that condition seems to have solved the problem.
I just added an output line directing the user to input the smaller population first to ensure that a user doesn't input 20000 and 500 causing the program to return the "towns are equal" message. Hopefully my instructor accepts it! Again, much appreciated!