编辑:全局变量作为作业的一部分受到限制(忘了提及)。
该计划旨在计算指定年数的每年预计人口。这是等式:
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 << "\n\nThe 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 << "\n\nError - starting population cannot be less than 2:" << endl;
cin >> pop;
}
return pop;
}
double get_annBirthRate()
{
double annBirthRate;
cout << "\n\nEnter the annual birth rate \n(a positive percentage in decimal form):" << endl;
cin >> annBirthRate;
while (annBirthRate < 0)
{
cout << "\n\nError - annual birth rate cannot be negative:" << endl;
cin >> annBirthRate;
}
return annBirthRate;
}
double get_annDeathRate()
{
double annDeathRate;
cout << "\n\nEnter the annual death rate \n(a positive percentage in decimal form):" << endl;
cin >> annDeathRate;
while (annDeathRate < 0)
{
cout << "\n\nError - death rate cannot be negative:" << endl;
cin >> annDeathRate;
}
return annDeathRate;
}
int get_numYears()
{
int numYears;
cout << "\n\nEnter the number of years to display:" << endl;
cin >> numYears;
while (numYears < 0)
{
cout << "\n\nError - 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;
}
答案 0 :(得分:0)
值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 << "\n\nThe projected population for the end of year "
<< num << " is " << P << endl;
注意:你不需要传递引用(如果你应该传递const double&amp;)