I am very new to C++. I have spent hours trying to get this to work. I have read and reread my textbook and tried emailing my prof but haven't been able to get any assistance as of yet. When I compile and run the program, it works sometimes and sometimes it doesn't. The counter does not advance past 1 for some reason. I recognize this is probably a very elementary problem for you guys, but as I said, I'm new to this. Any suggestions would be greatly appreciated. Thanks.
#include <iostream>
usingnamespace std;
int main()
{
int popA;
int popB;
double growthA;
double growthB;
int num;
int num2;
int sum1;
int sum2;
int counter;
cout<< “Enter the population of town A: ” <<endl;
cin>>popA;
cout<< “Enter the percentage growth rate of town A's population: ” <<endl;
cin>>growthA;
cout<<endl;
cout<< “Enter the population of town B: ” <<endl;
cin>>popB;
cout<< “Enter the percentage growth rate of town B's population: ” <<endl;
cin>>growthB;
cout<<endl;
num1 = 0;
num2 = 0;
sum1 = 0;
sum2 = 0;
counter = 0;
do
{
sum1 = popA + (growthA/100) * popA;
num1 = num1+sum1;
sum2= popB + (growthB/100) * popB;
num2 = num2+sum2;
counter++;
}
while num1 != num2;
cout<< “The number of years required for the populations of towns A and B to be equal is” <<counter<<endl;
cout<< “The population of towns A is: ”<<num1<<endl;
cout<< “The population of town B is: ”<<num2<<endl;
system(“pause”);
return 0;
}
I'm not sure how you can say this when it does not even compile. For example:
- num1 hasn't been defined
- your while loop: while num1 != num2;
should be while (num1 != num2);
1) Please next time post compiling code
2) Main problem you have is that the loop has a great chance to run infinitely: there is no guarantee that num1 will be equal to num2 at some point. In fact by feeding program random numbers it is hard to find numbers where it would stop
3) You have logic erors in your program:
a) your population growth formula does not account city growth: it depends on initial population and growth rate only, neither of which changes.
b) Your sum is wrong: just look what happens with population of 1000 and growth of 0.