Advertisement
enkov

Задача със структура (с функции и сортиране)

Nov 22nd, 2018
547
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 5.66 KB | None | 0 0
  1. /*
  2. В един супермаркет се прави малка програма за работа със стоките в него.
  3. Всяка стока се описва с име, производител, цена и налично количество.
  4. Въведете число n (5..50).
  5. Въведете данните за n стоки. Използвайте структура и функции.
  6.  
  7. Изведете информация за:
  8. 1. всички стоки в магазина;
  9. 2. стоките с производител „Elite“ с цена по-ниска от 5.25 лв;
  10. 3. стоките с максимална цена от наличните в повече от 100 единици;
  11. 4. за даден производител средната цена;
  12. 5. стоките, подредени по нарастваща цена, по метода на мехурчето;
  13. 6. стоките, подредени по намаляваща цена, по метода на пряката селекция.
  14. */
  15.  
  16. #include "stdAfx.h" // при нужда сменете или премахнете този ред, в зависимост от компилатора
  17. #include <iostream>
  18. #include <string>
  19. using namespace std;
  20.  
  21. const int MaxStocks = 50;
  22.  
  23. // глобална дефиниция на структурата, за да е видима от функциите извън main()
  24. struct Stock {
  25.     string Name;
  26.     string Maker;
  27.     float Price;
  28.     float Amount;
  29. };
  30.  
  31. Stock Stocks[MaxStocks + 1];  // правим и масива Stocks глобален, MaxStocks+1 елемента, за да работим с 1..MaxStocks
  32.  
  33. void EnterNumberOfStocks(int &n,  int aMax)
  34. {
  35.     do {
  36.         cout << "Enter the number of stocks (5.." << aMax << "): ";
  37.         cin >> n;
  38.     } while (n < 5 || n > aMax);
  39. };
  40.  
  41.  
  42. void EnterStock(Stock &aStock, int id) // въвеждане на един елемент от тип Stock
  43. {
  44.     cout << "Enter information for stock " << id << endl;
  45.     cout << " Name: ";
  46.     cin.get();  // flush the cin's buffer
  47.     getline(cin, aStock.Name);
  48.     cout << " Maker: ";
  49.     getline(cin, aStock.Maker);
  50.     cout << " Price: ";
  51.     cin >> aStock.Price;
  52.     cout << " Amount: ";
  53.     cin >> aStock.Amount;
  54. }
  55.  
  56. void EnterAllStocks(Stock StocksArr[], const int size)
  57. {
  58.     for (int i = 1; i <= size; i++)
  59.         EnterStock(StocksArr[i], i);
  60. }
  61.  
  62. void PrintStock(Stock aStock, const int id)
  63. {
  64.     cout << " " << id
  65.         << ": name: " << aStock.Name
  66.         << ", maker: " << aStock.Maker
  67.         << ", price: " << aStock.Price
  68.         << ", amount: " << aStock.Amount << endl;
  69. }
  70.  
  71. void PrintAllStocks(Stock StocksArr[], const int size)
  72. {
  73.     for (int i = 1; i <= size; i++)
  74.         PrintStock(StocksArr[i], i);
  75. }
  76.  
  77. void PrintStocksByMakerAndPrice(Stock StocksArr[], const int size, string aMaker, float aPrice)
  78. {
  79.     for (int i = 1; i <= size; i++)
  80.         if (StocksArr[i].Maker == aMaker && StocksArr[i].Price < aPrice)
  81.             PrintStock(StocksArr[i], i);
  82. }
  83.  
  84. void PrintMaximalPriceOverAmount(Stock StocksArr[], const int size, float anAmount)
  85. {
  86.     float maxPrice = 0.0;
  87.     for (int i = 1; i <= size; i++)
  88.     {
  89.         if (StocksArr[i].Amount > anAmount)
  90.         {
  91.             // ако е 1-вата стока с по-голяма наличност от указаната - запомняме веднага
  92.             if (maxPrice == 0)
  93.                 maxPrice = StocksArr[i].Price;
  94.             // проверяваме цената дали е по-голяма от най-голямата до момента
  95.             if (StocksArr[i].Price > maxPrice)
  96.                 maxPrice = StocksArr[i].Price;
  97.         }
  98.     }
  99.     if (maxPrice == 0.0)
  100.         cout << "No stocks with amount over " << anAmount << endl;
  101.     else
  102.         for (int i = 1; i <= size; i++)
  103.             if (StocksArr[i].Amount > anAmount && StocksArr[i].Price == maxPrice)
  104.                 PrintStock(StocksArr[i], i);
  105. }
  106.  
  107.  
  108. float AveragePriceByMaker(Stock StocksArr[], const int size, string aMaker, int &count)
  109. {
  110.     count = 0;
  111.     float sum = 0.0;
  112.     for (int i = 1; i <= size; i++)
  113.         if (StocksArr[i].Maker == aMaker)
  114.         {
  115.             count++;
  116.             sum += StocksArr[i].Price;
  117.         }
  118.     if (count > 0) return sum / count;
  119.     else return 0;
  120. }
  121.  
  122. void SortByPriceSelSort(Stock StocksArr[], const int size)
  123. {
  124.     for (int i = 1; i <= size; i++)
  125.     {
  126.         int max = i;
  127.         for (int j = i; j <= size; j++)
  128.             if (StocksArr[j].Price > StocksArr[max].Price)
  129.                 max = j;
  130.         swap(StocksArr[max], StocksArr[i]);
  131.     }
  132. }
  133.  
  134.  
  135. void SortByPriceBubbleSort(Stock StocksArr[], const int size)
  136. {
  137.     for (int i = 1; i <= size; i++)
  138.     {
  139.         for (int j = size; j > i; j--)
  140.             if (StocksArr[j].Price < StocksArr[j-1].Price)
  141.                 swap(StocksArr[j], StocksArr[j-1]);
  142.     }
  143. }
  144.  
  145. int main()
  146. {
  147.     int numStocks;
  148.     EnterNumberOfStocks(numStocks, MaxStocks);
  149.     EnterAllStocks(Stocks, numStocks);
  150.  
  151.     cout << "1. Information for all stocks: " << endl;
  152.     PrintAllStocks(Stocks, numStocks);
  153.  
  154.     cout << "2. Stocks with maker Elite and price under 5.25:" << endl;
  155.     PrintStocksByMakerAndPrice(Stocks, numStocks, "Elite", 5.25);
  156.  
  157.     cout << "3. Stocks with maximal price from these with amount over 100:" << endl;
  158.     PrintMaximalPriceOverAmount(Stocks, numStocks, 100);
  159.  
  160.     string theMaker;
  161.     cout << "4. Average price of stocks from maker (enter it): ";
  162.     cin.get();
  163.     getline(cin, theMaker);
  164.     int count;
  165.     float avg = AveragePriceByMaker(Stocks, numStocks, theMaker, count);
  166.     if (count == 0)
  167.         cout << " No stocks from the maker " << theMaker << endl;
  168.     else
  169.         cout << " Average price of stocks from maker " << theMaker << " is " << avg << endl;
  170.    
  171.     cout << "5. Stocks, sorted by Price min->max (BubbleSort: ";
  172.     SortByPriceBubbleSort(Stocks, numStocks);
  173.     PrintAllStocks(Stocks, numStocks);
  174.    
  175.     cout << "6. Stocks, sorted by Price max->min (SelectionSort: ";
  176.     SortByPriceSelSort(Stocks, numStocks);
  177.     PrintAllStocks(Stocks, numStocks);
  178. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement