首页 > 解决方案 > 使用函数,循环后,得到相同的值

问题描述

我得到了下面的代码。唯一的问题是在循环之后,人口总是相同的值。有什么问题?

在一个人口中,出生率是人口因出生而增加的百分比,而死亡率是人口因死亡而减少的百分比。编写一个程序,显示任意年的人口规模。该程序应要求提供以下数据:

#include <iostream>
#include <string>
using namespace std;
double get_data(double, string, string);
double population(double, double, double, int, int);


int main()
{
    double pop, birth, death;
    int movein, departures, years;
    double newpop;
    int i;

   cout << "This program calculates population change.\n";
    pop = get_data(2,
        "Enter the starting population size: ",
        "Starting population must be 2 or more.");
    birth = get_data(0,
        "Enter the annual birth rate (as % of current population): ",
        "Birth rate percent cannot be negative.");
    death = get_data(0,
        "Enter the annual death rate (as % of current population): ",
        "Death rate percent cannot be negative.");
    movein = get_data(0,
        "How many individuals move into the area each year? ",
        "Arrivals cannot be negative.");
    departures = get_data(0,
        "How many individuals leave the area each year? ",
        "Departures cannot be negative.");
    years = get_data(1,
        "For how many years do you wish to view population changes? ",
        "Years must be one or more.");
    
    cout << endl << endl
         << "Starting population: " << pop << endl;


    for (i = 1; i <= years; i++)
    {
        newpop = population(pop, birth, death, movein, departures);
        cout << "Population at the end of year " << i << " is " << newpop << endl;
    }

    system("PAUSE");
    return 0;


}

double get_data(double minValue, string prompt, string inputError) 
{
    double input;
    cout << prompt;
    cin >> input;
    while (input < minValue)
    {
        cout << inputError 
             << "\nPlease re-enter: ";
        cin >> input;
    }
    return input;
}

double population(double pop, double birth, double death, int movein, int departures)
{
    double newpop = pop + (birth * pop) / 100 - (death * pop) / 100 + movein - departures;
    return newpop;
}

标签: c++

解决方案


问题是你一次又一次地给你的函数同样的输入:

newpop = population(pop, birth, death, movein, departures);

简单的解决方法可能是消除变量newpop

for (i = 1; i <= years; i++)
{
    pop = population(pop, birth, death, movein, departures);
    cout << "Population at the end of year " << i << " is " << pop << endl;
}

或者如果你想保持详细:

for (i = 1; i <= years; i++)
{
    newpop = population(pop, birth, death, movein, departures);
    cout << "Population at the end of year " << i << " is " << newpop << endl;
    pop = newpop;
}

推荐阅读