如何增加人口/无休止的循环

时间:2016-04-20 04:13:50

标签: c++

我是一个初学者,他对我的学业作业有一些疑问。

使用我当前的代码,我陷入了一个无休止的循环,我假设是因为我的条件从未真正得到满足(Pop A大于Pop B)而且我不确定如何继续。我也不确定如何正确增加/计算A镇超过B镇所需的年数,但这是我到目前为止所做的。

#include <iostream>
#include <iomanip>
using namespace std;

int main()
{
    int townA;
    int townB;
    double growthA;
    double growthB;
    double finalA;
    double finalB;
    int years = 0;

    cout << "Enter the population of town A: ";
    cin >> townA;
    cout << "Enter the growth rate of town A: ";
    cin >> growthA;
    cout << "Enter the population of town B: ";
    cin >> townB;
    cout << "Enter the growth rate of town B: ";
    cin >> growthB;

    while ((townA <= 0) && (growthA <=0) && (townB > townA) && (growthB < growthA) && (growthB > 0))
    {
        cout << "Error: Values must be positive, please try again." << endl;
        cout << "Enter the population of town A: ";
        cin >> townA;
        cout << "Enter the growth rate of town A: ";
        cin >> growthA;
        cout << "Enter the population of town B: ";
        cin >> townB;
        cout << "Enter the growth rate of town B: ";
        cin >> growthB;
        cout << endl;
    }

    years = 0;
    while (townA <= townB)
    {
        finalA = ((growthA / 100) * (townA)) + townA;
        finalB = ((growthB / 100) * (townB)) + townB;
        cout << "It took Town A " << years << " years to exceed the population of Town B." << endl;
        cout << "Town A " << finalA << endl;
        cout << "Town B " << finalB << endl;
    }

        cout << "\n\n" << endl;    // Teacher required us to output it to the screen incase anyone is wondering why I have this block
        cout << setw(3) << "Town A" << setw(15) << "Town B" << endl;
        cout << setw(3) << growthA << "%" << setw(10) << growthB << "%" << endl;
        cout << setw(3) << townA << setw(7) << townB << endl;
        cout << "Year" << endl;
        cout << "--------------------------------------------" << endl;

    return 0;
}

1 个答案:

答案 0 :(得分:1)

您没有更新循环中townAtownB的值。因此,你永远不会离开循环。

此外,您需要在循环中增加years。使用:

while (townA <= townB)
{
   finalA = ((growthA / 100) * (townA)) + townA;
   finalB = ((growthB / 100) * (townB)) + townB;
   cout << "Town A " << finalA << endl;
   cout << "Town B " << finalB << endl;

   // Update the values of the key variables.
   ++years;
   townA = finalA;
   townB = finalB;
}

// This needs to be moved from the loop.
cout << "It took Town A " << years << " years to exceed the population of Town B." << endl;