Дана матрица. Найти сумму элементов в тех столбцах, которые не содержат отрицательные элементы. Количество столбцов и строк матрицы должен вводить пользователь. По введенным данным, динамически, должна выделиться память под матрицу. Матрицу заполнять случайными значениями, как отрицательными так и положительными. Вот пример работы программы:
#include <iostream>
#include <iomanip>
#include <ctime>
#include <cstdlib>
using namespace std;
int main()
{
srand(time(0)); // генерация случайных чисел
cout << "Enter the number of rows: "; // введите количество строк
int rows_number = 0;
cin >> rows_number;
cout << "Enter the number of columns: "; // введите количество столбцов
int columns_number = 0;
cin >> columns_number;
// динамическое создание двумерного массива вещественных чисел на десять элементов
int **ptrarray_a = new int* [rows_number]; // строки в массиве
for (int count = 0; count < rows_number; count++)
ptrarray_a[count] = new int [columns_number]; // столбцы
// заполнение массива
for (int count_row = 0; count_row < rows_number; count_row++)
for (int count_column = 0; count_column < columns_number; count_column++)
ptrarray_a[count_row][count_column] = rand() % 10 - 2; //заполнение массива случайными числами
for (int count_row = 0; count_row < rows_number; count_row++)
{
for (int count_column = 0; count_column < columns_number; count_column++)
cout << setw(2) << ptrarray_a[count_row][count_column] << " "; //вывод массива
cout << endl;
}
int *ptrarray = new int [columns_number]; // создание динамического массива
for (int count = 0; count < columns_number; count++)
ptrarray[count] = 0;
for (int count_column = 0; count_column < columns_number; count_column++)
{
for (int count_row = 0; count_row < rows_number; count_row++)
if (ptrarray_a[count_row][count_column] >= 0)
ptrarray[count_column] += ptrarray_a[count_row][count_column];
else
{
ptrarray[count_column] = 0;
break;
}
}
cout << endl;
for (int count = 0; count < columns_number; count++)
if (ptrarray[count] != 0)
cout << setw(2) << ptrarray[count] << " "; // печать первоначального массива
else
cout << setw(3) << " ";
cout << endl;
// удаление двумерного динамического массива
for (int count = 0; count < 2; count++)
delete []ptrarray_a[count];
delete [] ptrarray; // высвобождение памяти
return 0;
}
Смотрим на результат работы программы:
CppStudio.com
Enter the number of rows: 5 Enter the number of columns: 4 5 7 3 -1 2 3 3 6 5 4 0 2 3 5 2 -2 1 0 4 2 16 19 12
Комментарии
YourSpace_tym
// array-numbers.cpp : Defines the entry point for the console application. // created by YourSpace_tym #include "stdafx.h" #include "iostream" #include "cstdlib" #include "ctime" using namespace std; int main() { srand(time(NULL)); int r, c; int ** array; cout << "Count of rows : "; cin >> r; cout << "Count of columns : "; cin >> c; array = new int*[r]; for (int i = 0; i < r; i++) { array[i] = new int[c]; } for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { array[i][j] = -2 + rand() % 10; } } for (int i = 0; i < r; i++) { for (int j = 0; j < c; j++) { cout << array[i][j] << ' '; } cout << endl; } int sum; int p = 0; for (int i = 0; i < c; i++) { sum = 0; p = 0; for (int j = 0; j < r; j++) { sum += array[j][i]; if (array[j][i] < 0) { p = 1; continue; } } if (p != 1)cout << "Sum : " << sum << endl; } return 0; }Vladimir Belikov
#include <iostream> #include <iomanip> #include <stdlib.h> using namespace std; int getR(int _min, int _max) {return rand() % (_max - _min + 1) + (_min);} int main() { srand(time(NULL)); short x, y, sum; bool negative; cout << "Размер матрицы через пробел: "; cin >> x; cin >> y; int ** matrix = new int * [x]; for (unsigned short i = 0; i < x; ++i) matrix [i] = new int [y]; for (unsigned short i = 0; i < y; ++i) { negative = 0; sum = 0; for (unsigned short j = 0; j < x; ++j) { matrix [j][i] = getR (-1, 10); cout << setw (4) << matrix [j][i]; if (!negative) {if (matrix[j][i] < 0) negative = 1;} if (!negative) sum += matrix[j][i]; } !negative ? cout << " = " << sum : cout << " : Есть отрицательные числа"; cout << '\n'; } for (unsigned short i = 0; i < x; ++i) delete [] matrix [i]; delete [] matrix; return 0; }Smile Time
//30(Сумма элементов столбцов не содержащих отрицательных чисел) #include <iostream> #include <string> #include <ctime> #include <iomanip> using namespace std; void sumColumns(int**, short, short); inline void deleteMatrix(int**, short, short); int main() { srand(time(0)); short column, row; cout << "enter number of row: "; cin >> row; cout << "enter number of column: "; cin >> column; int **matrix; //хотелось бы и выделение памяти производить matrix = new int*[row]; //через инлайн, но что-то не вяжется... for (int i = 0; i < row; ++i) matrix[i] = new int[column]; sumColumns(matrix, row, column); deleteMatrix(matrix, row, column); system("pause"); return 0; } void sumColumns(int** tempMatrix, short row, short column) { for (int i = 0; i < row; ++i) { for (int j = 0; j < column; ++j) { cout << setw(3) << (tempMatrix[i][j] = rand() % 20 - 3) << " "; } cout << "\n"; } cout << "\n========================\n"; for (int i = 0; i < column; ++i) { int sum = 0; bool checkPositivity = 1; for (int j = 0; j < row; ++j) { sum += tempMatrix[j][i]; //суммирование столбцов if (tempMatrix[j][i] < 0) checkPositivity = 0; } if (checkPositivity == true) //если встретилось отрицательное cout << setw(3) << sum << " "; //число, сумма не выводится } cout << "\n========================\n"; } //освобождение памяти занимаемой матрицей inline void deleteMatrix(int** tempMatrix, short row, short column) { for (int i = 0; i < row; i++) delete[]tempMatrix[i]; }Smile Time
Немного недоглядел, при выводе результата, цифры съезжают, из-за не вывода отрицательных сумм.(может показать что работает неправильно)
cout << "\n============================\n"; for (int i = 0; i < column; i++) { for (int j = 0; j < row; j++) { sum += tempMatrix[j][i]; //суммирование столбцов if (tempMatrix[j][i] < 0) checkPositivity = 0; } if (checkPositivity == 1) //если встретилось отрицательное cout << setw(3) << sum << " "; //число, сумма не выводится else{ cout << " "; //этой строчки не хватало!!! } sum = 0; checkPositivity = 1; } cout << "\n============================\n"; }