Мне нужно проверить мои Population
, birth
и death
, в моей программе. Я хочу, чтобы Population
всегда начинал и никогда не позволял идти ниже 2
. Для birth
и death
Я никогда не хочу, чтобы они были меньше 0
. Как выполнить эту задачу? Если вам нужно какое-либо разъяснение, я могу предоставить. Я новичок на этом сайте.C++, где я могу поставить утверждение в классе или объекте для подтверждения рождения и смерти населения
#include <iostream>
#include <cmath>
#include <iomanip>
#include <string>
using namespace std;
class Population
{
private:
int current_pop;
int Births;
int annuel_births;
int deaths;
int annuel_deaths;
public:
void setpop(int);
int getpop(int);
void setborn(double);
void setdead(double);
double getdead(float deaths, int current_pop)
{
return deaths/current_pop;
};
double getborn(float Births, int current_pop)
{
return Births/current_pop;
};
};
void menu();
void Population::setpop(int people)
{
current_pop = people;
if (people < 2)
{
people = 2;
}
}
int Population::getpop(int people)
{
return current_pop;
}
void Population::setborn(double baby)
{
Births = baby;
if (baby < 0)
{
baby = 0;
}
}
void Population::setdead(double dead)
{
deaths = dead; // i tried to add the validation here but it still allows me to change it //below 0 same thing with the other validations
if (dead < 0)
{
dead = 0;
}
}
int main()
{
double Births = 0;
double Deaths = 0;
int people = 2;
Population location;
char choice;
cout << "Welcome to the population program.\nPlease select one of the menu items by entering a value 1-8. \n1 . Enter population, Annuel Births, Annuel Deaths.\n2 . Change Population.\n3 . Change Annuel Births.\n4 . Change annuel Deaths.\n5 . View current Population.\n6 . View Birthrate.\n7 . View DeathRate. \n8 . exit program." << endl;
do
{
const char Max_Choice = '8';
char getChoice(char);
choice = getChoice(Max_Choice);
switch (choice)
{
case '1': cout << "This is the town of Kakariko Village.\nPlease input the current population: "; cin >> people;
cout << "input the annuel number of births: "; cin >> Births;
cout << "input the annuel deaths in this village: "; cin >> Deaths;
cout << "==========================================" << endl;
menu();
char getChoice(char);
break;
case '2': cout << "ok you wish to change population!\nThis is the town of Kakariko Village.\nPlease input the current population: "; cin >> people;
cout << " " << endl;
menu();
char getChoice(char);
location.setpop(people); // calling function with variable as argument
cout << "current populaion = " << people << endl;
break;
case '3': cout << "you wish to change the number of annuel births\ninput the annuel number of births: "; cin >> Births;
location.setborn(Births);
cout << "your birthrate is: " << Births << endl;
cout << " " << endl;
menu();
char getChoice(char);
break;
case '4': cout << "ok you wish to change the annuel number of deaths\ninput the annuel deaths in this village: "; cin >> Deaths;
location.setdead(Deaths);
cout << " your death rate is: " << Deaths << endl;
cout << " " << endl;
menu();
char getChoice(char);
break;
location.setpop(people);
case'5': cout << "ok you wish to view population it's: " << people << endl;
break;
case'6':cout << "ok you wish to view the birthrate it's: " << location.getborn(Births, people) << endl;
cout << " " << endl;
menu();
char getChoice(char);
break;
case'7':cout << "ok you wish to view the deathrate it's: " << location.getdead(Deaths, people) << endl;
cout << " " << endl;
menu();
char getChoice(char);
break;
case'8':
return 0;
break;
}
} while (choice != '8'|| choice != '1'); cin >> choice;
system("pause");
return 0;
}
char getChoice(char max)
{
char choice = cin.get();
cin.ignore(256, '\n');
cin.clear();
while (choice < '1' || choice > max)
{
cout << "choice must be between 1 and " << max << ". "
<< "enter choice again.: "; choice = cin.get();
cin.ignore();
}
return choice;
}
void menu()
{
cout << "Please select one of the menu items by entering a value 1-8. \n1 . Enter population, Annuel Births, Annuel Deaths.\n2 . Change Population.\n3 . Change Annuel Births.\n4 . Change annuel Deaths.\n5 . View current Population.\n6 . View Birthrate.\n7 . View DeathRate. \n8 . exit program." << endl;
}
Возможно написать конструктор по умолчанию, который инициализирует их минимальными значениями, и необязательно предоставить конструктор, который принимает эти значения в качестве параметров и проверяет их? Кроме того, если значения недействительны, я бы предложил исключить исключение вместо того, чтобы устанавливать переменную в другое значение. Вы можете поймать это исключение и, например, отобразить сообщение пользователю. – cdhowie