Написати програмний код на С++
Дано два двомірних масиву однакових розмірів. Створити третій масив такого ж розміру, кожен елемент якого дорівнює 100, якщо відповідні елементи двох перших масивів мають однаковий знак, і дорівнює нулю в іншому випадку.
Має бути мінімум 3 функції: для зчитування, для розрахунку, для збереження результатів, вихідні дані ввести з текстового файлу, результат вивести на екран і в текстовий файл;
Ответы
Ответ:
#include <iostream>
#include <fstream>
using namespace std;
const int MAX_SIZE = 100;
void readArrays(int arr1[][MAX_SIZE], int arr2[][MAX_SIZE], int& rows, int& cols) {
ifstream inputFile("input.txt");
if (!inputFile) {
cout << "Unable to open input file." << endl;
return;
}
inputFile >> rows >> cols;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
inputFile >> arr1[i][j];
}
}
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
inputFile >> arr2[i][j];
}
}
inputFile.close();
}
void calculateResult(int arr1[][MAX_SIZE], int arr2[][MAX_SIZE], int result[][MAX_SIZE], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
if (arr1[i][j] == 0 || arr2[i][j] == 0) {
result[i][j] = 0;
} else if ((arr1[i][j] > 0 && arr2[i][j] > 0) || (arr1[i][j] < 0 && arr2[i][j] < 0)) {
result[i][j] = 100;
} else {
result[i][j] = 0;
}
}
}
}
void saveResult(int result[][MAX_SIZE], int rows, int cols) {
ofstream outputFile("output.txt");
if (!outputFile) {
cout << "Unable to open output file." << endl;
return;
}
outputFile << rows << " " << cols << endl;
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
outputFile << result[i][j] << " ";
cout << result[i][j] << " ";
}
outputFile << endl;
cout << endl;
}
outputFile.close();
}
int main() {
int arr1[MAX_SIZE][MAX_SIZE];
int arr2[MAX_SIZE][MAX_SIZE];
int result[MAX_SIZE][MAX_SIZE];
int rows, cols;
readArrays(arr1, arr2, rows, cols);
calculateResult(arr1, arr2, result, rows, cols);
saveResult(result, rows, cols);
return 0;
}
Цей код зчитує дані з файлу "input.txt", обчислює результат за вказаною формулою та записує його в файл "output.txt". Функція "readArrays" зчитує два масиви з файлу "input.txt". Функція "calculateResult" обчислює результат та зберігає його в третьому масиві. Функція "saveResult" записує результат у файл "output.txt" та виводить його на екран.
Объяснение: