Описать класс призма: объём, высота, количество граней, длинна сторон, площадь основания. Реализовать get- и set-методы для работы с элемент-данными класса. Организовать выбор (меню) входные и выходные данные. Защитить элемент-данные призмы от внешних кодов.

Рисунок 1 — Класс Призма
#include <iostream>
using namespace std;
class Prism
{
private:
double high, // высота призмы
vol, // объём призмы V = high * Sосн
length_side, // длинна сторон(граней) призмы
space_base; // площадь основания
int number_grain; // число боковых граней
public:
Prism(double h = 1, double lside = 1, int num = 3, double sbase = 10); // конструктор по умолчанию
void Sethigh(const double & ); // установить высоту призмы
void setLengthSide(const double & ); // установить длинну граней
void setGrain(const int & ); // установить количество боковых граней призмы
void setSpaceBase(const double &); // задать площадь основания призмы
double getHigh() const;
int getGrain() const; // вернуть количество боковых граней призмы
double getSpaceBase() const; // вернуть значение площади основания призмы
double getLengthSide() const; // вернуть значение длинны сторон призмы
double getVol(); // вернуть V призмы
};
int main()
{
Prism obj1; // создаём объект призма, активируется конструктор по умолчанию
int key; // выбор в меню
bool exit = false; //переменная-флаг цикла while
while (!exit) // начало while
{
cout << "Сделайте выбор:\n0 - выход; 1 - показать высоту призмы;\n2 - показать колличество боковых граней;"
<< " 3 - показать площадь основания;\n4 - показать длинну сторон призмы; 5 - показать объём призмы;\n"
<< "6 - установить высоту призмы; 7 - установить длинну сторон призмы; \n8 - установить количество граней; 9 - задать площадь основания\n>> ";
cin >> key;
double temp; // временная переменная для хранения аргументов
switch (key) // выбор действия
{
case 0: {exit = true; break;}
case 1: {cout << "Высота призмы = " << obj1.getHigh() << endl << endl; break;}
case 2: {cout << "Количество боковых граней = " << obj1.getGrain() << endl << endl; break;}
case 3: {cout << "Площадь основания = " << obj1.getSpaceBase() << endl << endl; break;}
case 4: {cout << "Длинна сторон призмы = " << obj1.getLengthSide() << endl << endl; break;}
case 5: {cout << "Объём призмы = " << obj1.getVol() << endl << endl; break;}
case 6: {cout << ":= "; cin >> temp; obj1.Sethigh(temp); break;}
case 7: {cout << ":= "; cin >> temp; obj1.setLengthSide(temp); break; }
case 8: {cout << ":= "; cin >> temp; obj1.setGrain(temp); break;}
case 9: {cout << ":= "; cin >> temp; obj1.setSpaceBase(temp);break;}
default: {cout << "Не верный выбор\n";}
} // конец выбора
} // конец while
return 0;
}
Prism::Prism(double h, double lside, int num, double sbase) // конструктор по умолчанию
: high(h), length_side(lside), number_grain(num), space_base(sbase), vol(h * sbase) // инициализаторы элемент-данных класса
{
// пустое тело конструктора
}
/// set-методы класса
void Prism::Sethigh(const double & h) // установить высоту призмы
{
high = (h > 0 ? h : 1); // если h не нулевое положительное число, то инициализировать высоту значением h, иначе единицей
}
void Prism::setLengthSide(const double & d) // установить длинну граней
{
length_side = (d > 0 ? d : 1); // если h не нулевое положительное число, то инициализировать высоту значением h, иначе единицей
}
void Prism::setGrain(const int & number) // установить количество боковых граней призмы
{
number_grain = (number > 0 ? number : 3); // минимальное количество граней - 3
}
void Prism::setSpaceBase(const double &number) // задать площадь основания призмы
{
space_base = (number > 0 ? number : 10); // пусть по умолчанию площадь равна 10
}
/// get-методы класса
double Prism::getHigh() const // вернуть значение высоты призмы
{
return high;
}
int Prism::getGrain() const // вернуть количество боковых граней призмы
{
return number_grain;
}
double Prism::getSpaceBase() const // вернуть значение площади основания призмы
{
return space_base;
}
double Prism::getLengthSide() const // вернуть значение длинны сторон призмы
{
return length_side;
}
double Prism::getVol() // вернуть V призмы
{
return vol = space_base * high;
}
Программа написана в ОС Linux. Для корректного отображения русского текста в Windows, прочитайте статью Кириллица в консоли. Результат работы программы показан на рисунке 1.
Комментарии
Ганнибал Лектер
Sancho уже сказал что не так, в добавок уточняй, что призма правильная.
Alex Antonyuk
#ifndef PRISM_H #define PRISM_H class Prism { private: float capacity; float height; int edges; float sideLength; float square; public: Prism(); float getCapacity() const; float getHeight() const; void setHeight(float); int getEdges() const; void setEdges( int); float getSideLength() const; void setSideLength(float); float getSquare() const; }; #endif // PRISM_H#include "Prism.h" #include <iostream> #include <cmath> using namespace std; Prism::Prism() { cout << "Prism height: "; cin >> height; cout << "Amount of edges: "; cin >> edges; cout << "Length of a side: "; cin >> sideLength; square = pow(sideLength, 2) * sqrt(3) / 4; capacity = square * height; } float Prism::getCapacity() const { return capacity; } float Prism::getHeight() const { return height; } void Prism::setHeight(float height1) { height = height1; square = pow(sideLength, 2) * sqrt(3) / 4; capacity = square * height; } int Prism::getEdges() const { return edges; } void Prism::setEdges(int edges1) { edges = edges1; } float Prism::getSideLength() const { return sideLength; } void Prism::setSideLength(float sideLength1) { sideLength = sideLength1; square = pow(sideLength, 2) * sqrt(3) / 4; capacity = square * height; } float Prism::getSquare() const { return square; }/* Describe a class prism: volume, height, number of faces, the long side, the base area. Implement get- and set-methods for working with the data element class. Organize selection (menu) inputs and outputs. Protect data element prism of the external code. by Oleksiy Antonyuk alex.antonyuk17@gmail.com 17.02.2017 */ #include <iostream> #include <Prism.h> using namespace std; char menu(); int main() { Prism prism; for (;;) { cout << endl; switch (menu()) { case '1': { float height; cout << "Height: "; cin >> height; if (height <= 0) { cout << "Height can't be <= 0" << endl; break; } prism.setHeight(height); break; } case '2': { int edges; cout << "Amount of edges: "; cin >> edges; if (edges <= 0) { cout << "An amount of edges can't be lower than 0" << endl; break; } prism.setEdges(edges); break; } case '3': { float sideLength; cout << "Length of the side: "; cin >> sideLength; if (sideLength <= 0) { cout << "The length of the side can't be <= 0" << endl; break; } prism.setSideLength(sideLength); break; } case '4': { cout << "Capacity - " << prism.getCapacity() << endl; break; } case '5': { cout << "Height - " << prism.getHeight() << endl; break; } case '6': { cout << "Amount of edges - " << prism.getEdges() << endl; break; } case '7': { cout << "Length of a side - " << prism.getSideLength() << endl; break; } case '8': { cout << "Square - " << prism.getSquare() << endl; break; } case 'q': { return 0; } } } } char menu() { cout << "Set the height - 1" << endl; cout << "Set the amount of edges - 2" << endl; cout << "Set the length of the side - 3" << endl << endl; cout << "Get the capacity - 4" << endl; cout << "Get the height - 5" << endl; cout << "Get the amount of edges - 6" << endl; cout << "Get the length of the side - 7" << endl; cout << "Get the square of the base - 8" << endl << endl; cout << "Quit - q" << endl; cout << "<< "; char option; cin >> option; return option; }gornyyvladimir
#include <vcl.h> #include <vector> #include <math.hpp> #include <iostream.h> #pragma hdrstop #pragma argsused class Prizma { private: double height, vol, length_side, space_base; size_t number_grain; public: Prizma(double h, double lside, size_t num, double sbase) { height = h; length_side = lside; space_base = sbase; number_grain = num; } void SetHeight (const double & h) { if(h>0.0) { height = h; } else height = 1.0; } void SetLength(const double & length) { if(length>0.0) { length_side = length; } else { length_side=1.0; } } void SetNumberGrain(const size_t & num) { if(num>3) { number_grain = num; } else { number_grain = 3; } } void SetBase(const double & base) { if(base>10.0) { space_base = base; } else { space_base = 10; } } double GetHeight() const { return height; } size_t GetNumGrain() const { return number_grain; } double GetBase() const { return space_base; } double GetLengthSide () const { return length_side; } double GetVol () { return vol=space_base*height; } }; int main(int argc, char* argv[]) { char key; bool exitProgram = false; Prizma prism(1.0,1.0,3,10.0); while(!exitProgram) { cout<<"Make choice:\n"<<"0 - exit; 1 - view height of prism;\n" <<"2 - view num of grains; 3 -view base of prism;\n" <<"4 - view length of side; 5 - view volume of prism\n" <<"6 - set prism height; 7 - set legth side;\n" <<"8 - set num of grains; 9 - set base square;\n"; cin>>key; switch (key) { case '0': exitProgram = true; break; case '1': cout<<"Height = "<<prism.GetHeight()<<'\n'; break; case '2': cout<<"Num of grains = "<<prism.GetNumGrain()<<'\n'; break; case '3': cout<<"Base = "<<prism.GetBase()<<'\n'; break; case'4': cout<<"Length of side = "<<prism.GetLengthSide()<<'\n'; break; case'5': cout<<"Volume = "<<prism.GetVol()<<'\n'; break; case'6': { double height; cout<<"Enter height: "; cin>>height; prism.SetHeight(height); break; } case '7': { double length; cout<<"Enter length: "; cin>>length; prism.SetLength(length); break; } case '8': { size_t num; cout<<"Enter num of grains: "; cin>>num; prism.SetNumberGrain(num); break; } case '9': { double base; cout<<"Enter base: "; cin>>base; prism.SetBase(base); break; } } } system("pause"); return 0; }Arthur
#include<iostream> #include<cmath> #include<iomanip> #include<conio.h> using namespace std; class Prizma { private: int n; //кол-во граней основания призмы float l; //длина грани основания призмы float h; //высота призмы public: void setn () //инициализируем кол-во и длину граней основания призмы { cout<<"Введите количество граней основания призмы: "; cin>>n; if(n<0) { cout<<"Неверный ввод!\n"; setn();} } void setl() { cout<<"\nВведите длину грани основания призмы: "; cin>>l; if(l<0) {cout<<"Неверный ввод!\n"; setl();} } void seth () //инициализируем высоту призмы { cout<<"Введите высоту призмы: "; cin>>h; if(h<0) {cout<<"Неверный ввод!\n"; seth();} } float prizmS() { float S = n*l*l/(4*tan(3.14/n)); return S; } float prizmV() { return (prizmS()*h) ; } }; /////////////////////////////////////////////////////////////////// int main() { setlocale(LC_CTYPE, "rus"); Prizma prizm; char vibor; bool ex(1); while(ex) { cout<<"\nСделайте выбор:" <<"\n1 - вычислить площадь основания призмы" <<"\n2 - вычислить объем призмы" <<"\n3 - выход" <<"\nВаш выбор: "; vibor = getche(); getch(); switch(vibor) { case '1': { prizm.setl(); prizm.setn(); cout<<fixed<<setprecision(1)<<"S = "<<prizm.prizmS()<<endl; break; } case '2': { prizm.setl(); prizm.setn(); prizm.seth(); cout<<fixed<<setprecision(1)<<"V = "<<prizm.prizmV()<<endl; break; } case '3': {ex = 0; break;} default: cout<<"\nНедопустимый ввод!"<<endl; } if(vibor!='3') { cout<<"\nПовторить? да - 1, нет - 0: "; cin>>ex; } } return 0; }Sancho
Если у меня введены длинна сторон и количество граней получаю площадь основания. Если после этого ввожу новую площадь — что меняется? Длинна или количество сторон? Плохо поставленная задача.