Advertisement
Maxty

bryły

Jan 23rd, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. /*Zdefiniuj klase bazową Bryła oraz pochodne Sześcian i Kula.
  2. Uwzględnij polimorficzną metodę obliczającą objętość.
  3. Napisz program obliczający średnią objętość brył w danej kolekcji vector<Bryła*>*/
  4.  
  5. #include <iostream>
  6. #include <vector>
  7. #define PI 3.14
  8. #include <time.h>
  9. #include <stdlib.h>
  10. using namespace std;
  11.  
  12. class Bryla{
  13. public:
  14. virtual double volume()=0;
  15. };
  16.  
  17. class Szescian : public Bryla{
  18. private:
  19. double s;
  20. public:
  21. Szescian (double s1):s(s1){}
  22. double volume(){
  23. return s*s*s;
  24. }
  25. };
  26.  
  27. class Kula:public Bryla{
  28. private:
  29. double r;
  30. public:
  31. Kula(double r1):r(r1){}
  32. double volume(){
  33. return 4/3*PI*r*r*r;
  34. }
  35. };
  36.  
  37. double meanVolume(vector <Bryla*> v){
  38. vector <Bryla*>:: iterator it =v.begin();
  39. double sum=0;
  40. while(it != v.end()){
  41. sum+=(*it)->volume();
  42. it++;
  43. }
  44. return sum/v.size();
  45. }
  46. void fillCollection(vector <Bryla*> & v, int n){
  47. for(int i=0; i<n; i++){
  48. switch(rand()%2+1){
  49. case 1:
  50. v.push_back(new Szescian(rand()%5+1));
  51. break;
  52. case 2:
  53. v.push_back(new Kula(rand()%5+1));
  54. break;
  55. }
  56. }
  57. }
  58. void displayCollection(vector <Bryla*> v){
  59. vector <Bryla*>:: iterator it = v.begin();
  60. while(it!=v.end()){
  61. if(dynamic_cast<Szescian*>(*it))
  62. cout << "Szescian: ";
  63. else
  64. cout << "Kula: ";
  65. cout << (*it)->volume() << endl;
  66. it++;
  67. }
  68. }
  69. int main(){
  70. srand(time(NULL));
  71. vector<Bryla*> kolekcja;
  72.  
  73. fillCollection(kolekcja,5);
  74. displayCollection(kolekcja);
  75. cout <<"Srednia objetosc: " << meanVolume(kolekcja) << endl;
  76.  
  77. return 0;
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement