Advertisement
krzotki

dynamiczne macierze............

Jan 19th, 2020
96
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.75 KB | None | 0 0
  1. // ConsoleApplication22.cpp : Defines the entry point for the console application.
  2. //
  3.  
  4. #include "stdafx.h"
  5. #include "iostream"
  6. #include "stdio.h"
  7. #include "stdlib.h"
  8. #include "time.h"
  9. #include "iomanip"
  10.  
  11. using namespace std;
  12. int getRandomInt(int min, int max);
  13. void randomMatrix(int **matrix, int rows, int cols, int min, int max);
  14. void displayMatrix(int **m, int rows, int cols);
  15. void addMatrices(int **m1, int **m2, int rows, int cols);
  16.  
  17. int main()
  18. {
  19.     srand(time(NULL));
  20.     int min = -5, max = 5;
  21.     int rows, cols;
  22.     cout << "Podaj wymiary macierzy : ";
  23.     cin >> cols >> rows;
  24.     cout << endl << "Podaj min max: ";
  25.     cin >> min >> max;
  26.     int *m1 = NULL;
  27.     int *m2 = NULL;
  28.     randomMatrix(&m1, rows, cols, min, max);
  29.     randomMatrix(&m2, rows, cols, min, max);
  30.  
  31.     displayMatrix(&m1, rows, cols);
  32.     displayMatrix(&m2, rows, cols);
  33.  
  34.     addMatrices(&m1, &m2, rows, cols);
  35.     displayMatrix(&m1, rows, cols);
  36.     return 0;
  37. }
  38.  
  39. void displayMatrix(int **m, int rows, int cols)
  40. {
  41.     int cellSize = 4;
  42.  
  43.     for (int i = 0; i < rows; i++)
  44.     {
  45.         for (int x = 0; x < cols; x++)
  46.         {
  47.             cout << setw(cellSize);
  48.             cout << *(*m + i*cols +x);
  49.         }
  50.         cout << endl;
  51.     }
  52.     cout << endl;
  53. }
  54. int getRandomInt(int min, int max)
  55. {
  56.     return rand() % (max - min + 1) + min;
  57. }
  58.  
  59. void randomMatrix(int **matrix, int rows, int cols, int min, int max)
  60. {
  61.     int *m;
  62.     m = (int*)calloc(rows*cols, sizeof(int));
  63.  
  64.     for (int i = 0;i < rows;i++)
  65.     {
  66.         for (int x = 0;x < cols;x++)
  67.         {
  68.             *(m + i * cols + x) = getRandomInt(min, max);
  69.         }
  70.     }
  71.  
  72.     *matrix = (int*)realloc(m,rows*cols*sizeof(int));
  73.  
  74. }
  75. void addMatrices(int **m1, int **m2,int rows,int cols)
  76. {
  77.  
  78.     for (int i = 0;i < rows;i++)
  79.     {
  80.         for (int x = 0;x < cols;x++)
  81.         {
  82.             *(*m1+i*cols+x) += (int)*(*m2 + i * cols + x);
  83.         }
  84.  
  85.     }
  86.  
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement