First of all, formatting the code would have given line numbers and made this easier :-(
Also, indentation!
Your
while(newpopA < newpopB)
needs an opening brace after it and a closing brace after
numOfYears++
newpopA and newpopB are uninitialised, so there's a good chance your loop may never run, regardless of the values of popA and popB.
Even if the loop was working, you're never actually incrementing newpopA or newpopB, only assigning the same value to them everytime, plus omitting output of the final values.
Two rules you could have followed that would have saved you here:
Explicitly initialise all variables before use (maybe define them just before using, that would have helped too)
prefer
int x = 0;
to
int x;
Always use braces to denote the block of if, while, for, do-while, etc. statements, even if the block is a single line or missing.
prefer
1 2 3 4
|
if (x > 0)
{
do_something();
}
|
to
1 2
|
if (x > 0)
do_something();
|
See suggested corrections below; I'm unsure of the actual growth algorithm, what you showed up there suggests you want to add the same percentage of the original population every year but I've chosen to just increase the current population by the same percentage every year, to highlight the ambiguity of the question.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
|
#include<iostream>
using namespace std;
int main()
{
double popA(0.0), popB(0.0);
cout << "Enter population for town A: ";
cin >> popA;
cout << "Enter population for town B (Must be larger than town A): ";
cin >> popB;
if (popA < popB)
{
double rateA(0.0), rateB(0.0);
cout << "Enter the growing rate of town A: ";
cin >> rateA;
cout << "Now enter the growing rate of Town B: ";
cin >> rateB;
if (rateA <= rateB)
{
cout << "Invalid ";
}
else
{
int numOfYears = 0;
while (popA < popB)
{
popA += (popA * (rateA / 100.0));
cout << "Population A: " << popA << endl;
popB += (popB * (rateB / 100.0));
cout << "Population B: " << popB << endl;
cout << "after " << ++numOfYears << " years" << endl;
}
}
}
else
{
cout << "Your input was invalid";
}
return 1;
}
|