更新迭代结果

Update iteration result

本文关键字:结果 迭代 更新      更新时间:2023-10-16

编辑:全局变量作为赋值的一部分受到限制(忘了提到这一点)。

该计划旨在计算指定年数内每年的预计人口。这是等式:

N = P(1 + B)(1 - D)

其中N是新的人口规模,P是以前的人口规模,B是出生率,D是死亡率。B 和 D 是小数。

所以我的问题是我只能得到第一次迭代的结果,而且我不知道如何更新结果,使其乘以 (1 + B) 和 (1 - D)。我的猜测是它与其中一个组合赋值运算符有关,但我还没有成功。

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int get_pop();
int get_numYears();
double get_annBirthRate();
double get_annDeathRate();
double pop_new(int& A, double& B, double& C, double& D);
int main()
{
    int P,
    num,
    Y;
    double B,
    D,
    N;
    P = get_pop();
    B = get_annBirthRate();
    D = get_annDeathRate();
    Y = get_numYears();
    for (num = 1; num != Y; num++)
    {
        N = pop_new(P, B, D, N);
        cout << "nnThe projected population for the end of year " << num << " is " << N << endl;
        cin.ignore();
    }
    return 0;
}
int get_pop()
{
    int pop;
    cout << "Enter the starting population:" << endl;
    cin  >> pop;
    while (pop < 2)
    {
        cout << "nnError - starting population cannot be less than 2:" << endl;
        cin  >> pop;
    }
    return pop;
}

double get_annBirthRate()
{
    double annBirthRate;
    cout << "nnEnter the annual birth rate n(a positive percentage in decimal form):" << endl;
    cin  >> annBirthRate;
    while (annBirthRate < 0)
    {
        cout << "nnError - annual birth rate cannot be negative:" << endl;
        cin  >> annBirthRate;
    }
    return annBirthRate;
}

double get_annDeathRate()
{
    double annDeathRate;
    cout << "nnEnter the annual death rate n(a positive percentage in decimal form):" << endl;
    cin  >> annDeathRate;
    while (annDeathRate < 0)
    {
        cout << "nnError - death rate cannot be negative:" << endl;
        cin  >> annDeathRate;
    }
    return annDeathRate;
}

int get_numYears()
{
    int numYears;
    cout << "nnEnter the number of years to display:" << endl;
    cin  >> numYears;
    while (numYears < 0)
    {
        cout << "nnError - number of years cannot be less than 1:" << endl;
        cin  >> numYears;
    }
    return numYears;
}
double pop_new(int& P, double& B, double& D, double& N)
{
    N = P * (1 + B) * (1 - D);
    return N;
}

值 P、B 和 D 不会更改。

来得及:

double pop_new(int P, double B, double D)
{
   double N = P * (1 + B) * (1 - D);
   return N;
}

和:

P = pop_new(P, B, D);
cout << "nnThe projected population for the end of year " 
     << num << " is " << P << endl;

注意:你不需要传递引用(如果,你应该传递常量双倍&)