2016-04-20 6 views
1

私は学校の宿題に関するいくつかの質問がある初心者です。人口増減の方法/ neverendingループ

私の現在のコードでは、条件が実際には決して満たされない(ポップAがポップ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

あなたは、ループ内で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; 
+0

@TonyD、もちろん:) –