gpt4 book ai didi

c++ - 我类的私有(private)变量在 C++ 中不起作用

转载 作者:行者123 更新时间:2023-11-30 03:42:12 24 4
gpt4 key购买 nike

<分区>

BR 和 DR 成员函数的输出只给我零。我猜我要么没有正确分配私有(private)成员,要么没有正确使用它们。我知道有更简单的方法可以在不类的情况下做到这一点,但遗憾的是,这就是我的教授想要完成的方式。请帮忙。

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

class Population
{
private:
//private variables
int births, deaths, population;
public:
//Member functons
void setpop(int); //sets population value
void setB(int); //sets birth value
void setD(int); //sets death value
double BR() const; //calculates birth-rate
double DR() const; //calculates death-rate
};
void Population::setpop(int p)
{
population = p; //assigns local variable from before to private member
}

void Population::setB(int b)
{
births = b; //assigns local variable from before to private member in class
}

void Population::setD(int d)
{
deaths = d; //assigns local variable from before to private member in class
}

double Population::BR() const
{
cout<<endl;
return births/population; //birth-rate
}
double Population::DR() const
{
cout<<endl;
return deaths/population; //death-rate
}

int main()
{
int localpopulation, localbirths, localdeaths; //local as in local variable
cout<<"Birth-Rate and Death-Rate program: "<<endl;
cout<<"Enter the population: ";
cin>>localpopulation;
//if statements to make sure the values qualify
if (localpopulation<1)
{
cout<<"Invalid population. Try again: ";
cin>>localpopulation;
}
cout<<endl;
cout<<"Enter the number of births: ";
cin>>localbirths;
if (localbirths<0)
{
cout<<"Invalid births. Try again: ";
cin>>localbirths;
}
cout<<endl;
cout<<"Enter deaths: ";
cin>>localdeaths;
if (localdeaths<0)
{
cout<<"Invalid deaths. Try again: ";
cin>>localdeaths;
}
Population object;
object.setpop(localpopulation);
object.setB(localbirths);
object.setD(localdeaths);
cout<<endl;
cout<<"The Birth-Rate is: "<<fixed<< setprecision(2)<<object.BR();
cout<<endl;
cout<<"The Death-Rate is: "<<fixed<< setprecision(2)<<object.DR();

}

此代码的示例输出:

出生率和死亡率程序:输入人口:1000

输入出生人数:30

输入死亡人数:20

出生率是:0.00

死亡率是:0.00

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com