Advertisement
STANAANDREY

pc9 6

Nov 25th, 2022
753
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.56 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <stdbool.h>
  4. #include <string.h>
  5. #define NAME_MAX_LEN 30
  6.  
  7. typedef struct{
  8.   char name[NAME_MAX_LEN];
  9.   double quantity, price;
  10. } Prod;
  11.  
  12. Prod *exists(Prod prods[], const char *const name, int uniqueNr) {
  13.   for (int i = 0; i < uniqueNr; i++) {
  14.     if (!strcmp(prods[i].name, name)) {
  15.       return &prods[i];
  16.     }
  17.   }
  18.   return NULL;
  19. }
  20.  
  21. Prod readProd(void) {
  22.   Prod prod;
  23.   scanf("%s %lf %lf", prod.name, &prod.quantity, &prod.price);
  24.   return prod;
  25. }
  26.  
  27. void displayProd(Prod prod) {
  28.   printf("%s %g, %g\n", prod.name, prod.quantity, prod.price);
  29. }
  30.  
  31. void processProd(Prod uniqueProds[], Prod prod, double *const totalPrice, int *const uniqueNr) {
  32.   Prod *target = exists(uniqueProds, prod.name, *uniqueNr);
  33.   if (target) {
  34.     target->quantity += prod.quantity;
  35.     target->price += prod.quantity * prod.price;
  36.   } else {
  37.     Prod aux = {
  38.       .quantity = prod.quantity,
  39.       .price = prod.price * prod.quantity
  40.     };
  41.     strcpy(aux.name, prod.name);
  42.     uniqueProds[*uniqueNr] = aux;
  43.     ++*uniqueNr;
  44.   }
  45.   *totalPrice += prod.quantity * prod.price;//*/
  46. }//*/
  47.  
  48. int main(void) {
  49.   int n, uniqueNr = 0;
  50.   scanf("%d", &n);
  51.   Prod *uniqueProds = (Prod*)malloc(sizeof(Prod) * n);
  52.   double totalPrice = .0;
  53.  
  54.   for (int i = 0; i < n; i++) {
  55.     Prod prod = readProd();
  56.     processProd(uniqueProds, prod, &totalPrice, &uniqueNr);
  57.   }
  58.  
  59.   for (int i = 0; i < uniqueNr; i++) {
  60.     displayProd(uniqueProds[i]);
  61.   }
  62.  
  63.   printf("global price: %g\n", totalPrice);
  64.   free(uniqueProds);//*/
  65.   return 0;
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement