如何改用求和语句来更改我的程序

How can I change my program by using a summing statement instead?

本文关键字:我的 程序 何改用 求和 语句      更新时间:2023-10-16

我的 c++ 任务是编写一个程序,按年份显示从 1985 年至今每个国家(墨西哥和美国)的人口估计值。将总体四舍五入到最接近的整数,并在三列中显示信息。完成此操作后,我将修改程序,使其在墨西哥人口超过美国人口之前显示相同的信息。我正确地完成了程序,当我运行它时,它给了我正确的信息,除了我的教授之外,所有人都给了我 0 分,因为他希望我不要使用 POW 函数,而是一个求和语句,我不知道我该怎么做,这对我来说听起来更复杂。这是我写的程序,我只是不知道如何使用求和语句来更改它:

//Program to compute when Mexico's pop exceeds the US pop
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main()
{
    int Years;
    double UsPop, MxPop;
    cout<<setw(7)<<"Year"<<setw(13)<<"US Pop"<<setw(13)<<"Mex Pop"<<endl;
    cout<<setprecision(0)<<fixed;
    for(Years=1985;Years<=2014;Years++)
    {
        UsPop=243000000.0*(pow(1.007,(Years-1984)));
        MxPop=78000000*pow(1.033,(Years-1984));
        cout<<setw(7)<<Years<<setw(13)<<UsPop<<setw(13)<<MxPop<<endl;
    }
}

我不确定您所说的"求和语句"是什么意思,因为看起来您的问题不需要"+"操作。

在任何情况下,您都不必使用 pow ,您只需在每次迭代时覆盖美国和墨西哥的人口数量,只需使用该指标相乘即可。

下面是一个示例:

int main()
{
    int Years;
    double UsPop=243000000.0;
    double MxPop=78000000;
    cout<<setw(7)<<"Year"<<setw(13)<<"US Pop"<<setw(13)<<"Mex Pop"<<endl;
    cout<<setprecision(0)<<fixed;
    double usIndicator = 1.007;
    double mexIndicator = 1.033;
    for(Years=1985;Years<=2014;Years++)
    {
        UsPop=UsPop*usIndicator;
        MxPop=MxPop*mexIndicator;
        cout<<setw(7)<<Years<<setw(13)<<UsPop<<setw(13)<<MxPop<<endl;
    }
}

也许你的教授希望你编写自己的Pow函数,而不是使用数学库中的函数?您可以尝试替换您的:

for(Years=1985;Years<=2014;Years++)
{
    UsPop=243000000.0*(pow(1.007,(Years-1984)));
    MxPop=78000000*pow(1.033,(Years-1984));
    cout<<setw(7)<<Years<<setw(13)<<UsPop<<setw(13)<<MxPop<<endl;
}

for (Years = 1985; Years <= 2014; Years++)
{
             UsPop = 243000000.0 * (myPow((Years - 1985), 1.007));
             MxPop = 78000000 * (myPow((Years - 1985), 1.033));
}

您的 Pow 函数将类似于:

    double myPow(double flag, double number)
    {
        double pow = number;
        //You can edit my formula to match "summing statement" as  your professor require .
        for (int i = 0; i < flag; i++)
        {
            pow *= number; //If I'm not mistaken, you should split it up to "Plus" then you will get your "summing statement".
        }
        return pow;
    }

两者的结果相同:

1) 299564530.595318/206587599.027265
---------------------------
2) 299564530.595318/206587599.027265
相关文章: