gpt4 book ai didi

c++ - 如何增加人口/永无止境的循环

转载 作者:行者123 更新时间:2023-11-30 05:28:37 25 4
gpt4 key购买 nike

我是初学者,对学校作业有一些疑问。

使用我当前的代码,我陷入了一个永无止境的循环,我假设这是因为我的条件从未真正满足(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;
}

最佳答案

您没有在循环中更新 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;

关于c++ - 如何增加人口/永无止境的循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36733677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com