#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#include <locale>
using namespace std;
// Тип данных. По условию char
typedef char data_t;
// Размерность матрицы
const size_t DIM = 5;
// Интервал значений для генерации матрицы
const data_t MIN = -50;
const data_t MAX = 50;
// Генерация значений матрицы
template<size_t DIM>
void fillMatrix(data_t(&matrix)[DIM][DIM])
{
size_t size = DIM*DIM;
data_t *arr = reinterpret_cast<data_t*> (matrix);
while (size--)
{
*arr++ = static_cast<data_t> (static_cast<double> (rand()) / RAND_MAX * (MAX - MIN) + MIN);
}
}
// Печать значений матрицы
template<size_t DIM>
void printMatrix(const char* const msg, const data_t(&matrix)[DIM][DIM])
{
cout << msg << endl;
for (size_t row = 0; row < DIM; ++row)
{
for (size_t col = 0; col < DIM; ++col)
{
cout << setw(4) << static_cast<int> (matrix[row][col]) << ' ';
}
cout << endl;
}
}
// Сумма 1м способом
template<size_t DIM>
int diagSum1(const data_t(&matrix)[DIM][DIM])
{
int sum = 0;
for (size_t i = 0; i < DIM; ++i)
{
sum += matrix[i][i];
}
return sum;
}
// Сумма 2м способом
template<size_t DIM>
int diagSum2(const data_t(&matrix)[DIM][DIM])
{
int sum = 0;
size_t size = DIM;
const data_t * arr = reinterpret_cast<const data_t*> (matrix);
while (size--)
{
sum += *arr;
arr += DIM + 1;
}
return sum;
}
int main()
{
locale::global(locale(""));
srand(time(0));
// Матрица
data_t m[DIM][DIM];
// Заполним матрицу
fillMatrix(m);
// Распечатать
printMatrix("Матрица:", m);
// Результат
cout << "Сумма по индексам:" << diagSum1(m) << endl
<< "Сумма по адресам:" << diagSum2(m) << endl;
#ifdef __WIN32
system("pause");
#endif
return 0;
}
Матрица:
-49 31 16 39 -30
-2 14 12 -40 -2
-23 -7 18 7 19
-19 6 25 35 46
0 -7 -13 -5 -10
Сумма по индексам:8
Сумма по адресам:8
#include <iostream>
#include <iomanip>
#include <fstream>
using namespace std;
const int N = 5;
double m[N][N];
int main()
{
double s = 0;
ifstream inputStream("tempfile.txt");
for (int i = 0; i < N; ++i)
{
for (int j = 0; j < N; ++j)
{
inputStream >> m[i][j];
}
}
int i = N;
double* ptr = reinterpret_cast<double*> (m);
while (i--)
{
s += *ptr;
ptr += N + 1;
}
cout << "\nResults s: " << s << endl;
#ifdef __WIN32
system("pause");
#endif
return 0;
}
#ifdef __WIN32
system("pause");
#endif
double* ptr = reinterpret_cast<double*> (m);
Если Вы уже зарегистрированы на Портале - войдите в систему, если Вы еще не регистрировались - пройдите простую процедуру регистрации.