需要更新for循环中的值

时间:2015-03-03 02:58:53

标签: c++

我正在尝试使用for循环创建一个表,输出年份,出生人数,死亡人数和新人口。我试图找出如何获得它,以便新的人口价值存储到下一年并正确积累。现在它只是重复所有年份的初始值。只是寻找一些提示,指出我正确的方向。感谢

void tabOut(int& numYears, unsigned int& P, double& B, double& D)
{
int year;
unsigned int N = (P + B * P - D * P);
cout << "Year\tNumber of births\tNumber of deaths\tNew population\n";
cout << "-------------------------------------------------------\n";

for (int year = 0; year <= numYears; ++year)
{
        cout << year << "\t" << (P * B) << "\t" << setw(8) << (P * D) <<     "\t" << setw(8) << (N) << endl;

    cout << "-------------------------------------------------\n";
}
}

1 个答案:

答案 0 :(得分:0)

这有帮助吗?

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

void tabOut(int numYears, unsigned int P, double B, double D)
{
    int year;

    cout << "Year\tNumber of births\tNumber of deaths\tNew population\n";
    cout << "-------------------------------------------------------\n";

    for (int year = 0; year < numYears; ++year)
    {
        unsigned int N = (P + (B * P) - (D * P));
        cout << (year + 1) << "\t" << ceil(P * B) << "\t" << setw(8) << ceil(P * D) <<     "\t" << setw(8) << (N) << endl;
        P = N;

        cout << "-------------------------------------------------\n";
    }
}

int main(int, char**)
{
    int years = 10;
    unsigned int population = 100;
    double births = 0.35;
    double deaths = 0.25;

    tabOut(years, population, births, deaths);
}

您没有在循环的后续迭代中执行计算,因此结果将始终相同。