Mail.ruПочтаМой МирОдноклассникиВКонтактеИгрыЗнакомстваНовостиКалендарьОблакоЗаметкиВсе проекты

C++ напишите код к задаче пожалуйста

name no Ученик (45), закрыт 1 месяц назад
Дан двухмерный массив, состоящий из NxM (10<= N и M <=1000) целочисленных
элементов. Размерность массива вводить с клавиатуры. Написать функцию нахождения суммы элементов массива кратных 5 и не
кратных 2. Функция должна возвращать значение булевской переменной в зависимости
есть или нет элементы массива кратные 5 и не кратные 2. Сумму элементов массива
вернуть с помощью формального параметра (ссылочной переменной).
Лучший ответ
Николай Веселуха Высший разум (361120) 1 месяц назад
 #include    
#include
#include
#include
#include

using namespace std;
using T = int;
using sum_t = long long;

size_t count(const char* prompt, size_t mn, size_t mx) {
size_t value = -1;
while (value < mn || value > mx) {
cout << prompt;
cin >> value;
cin.ignore(0x1000, '\n');
}
return value;
}

void fill_random(vector>& mx, T a, T b) {
if (a > b) swap(a, b);
uniform_int_distribution uid(a, b);
mt19937 gen{ random_device()() };
for (auto& row : mx) {
for (auto& x : row) {
x = uid(gen);
}
}
}

void show(const vector>& mx, const streamsize w) {
for (const auto& row : mx) {
for (auto x : row) {
cout << ' ' << setw(w) << x;
}
puts("");
}
puts("");
}

bool is_sum(const vector>& mx, const T yes, const T no, sum_t& sum) {
for (const auto& row : mx) {
for (auto x : row) {
if (0 == x % yes && x % no != 0) {
sum += x;
}
}
}
return sum > 0;
}

int main() {
constexpr size_t h = 10;
constexpr size_t w = 1000;
auto n = count("N: ", h, w);
auto m = count("M: ", h, w);
vector> mx(n, vector(m));
T a = 10;
T b = 99;
fill_random(mx, a, b);
auto width = static_cast(log10(b) + 1);
show(mx, width);
constexpr auto yes = 5;
constexpr auto no = 2;
sum_t sum{};
if (is_sum(mx, yes, no, sum)) {
cout << "Sum: " << sum << '\n';
} else {
puts("Not found!");
}
}
name noУченик (45) 1 месяц назад
Дядя Коля, а как без векторов сделать это задание тоже(
Николай Веселуха Высший разум (361120) name no, ну и где мне публиковать обновлённый код? В комментариях он не поместится, а если картинкой, то для вас будет неудобно.
Остальные ответы
Даниил Орлов Мастер (1620) 1 месяц назад
 #include  

const int MAX_SIZE = 1000;

bool findNumbers(int arr[MAX_SIZE][MAX_SIZE], int N, int M, int& sum)
{
bool hasNumbers = false;
sum = 0;

for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
if (arr[i][j] % 5 == 0 && arr[i][j] % 2 != 0)
{
hasNumbers = true;
sum += arr[i][j];
}
}
}

return hasNumbers;
}

int main()
{
int N, M;
int arr[MAX_SIZE][MAX_SIZE];

std::cout << "Введите размеры массива (N и M): ";
std::cin >> N >> M;

std::cout << "Введите элементы массива:\n";
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
std::cin >> arr[i][j];
}
}

int sum;
bool hasNumbers = findNumbers(arr, N, M, sum);

if (hasNumbers)
{
std::cout << "Есть элементы кратные 5 и не кратные 2. Сумма таких элементов: " << sum << std::endl;
}
else
{
std::cout << "Таких элементов нет." << std::endl;
}

return 0;
}
name noУченик (45) 1 месяц назад
Не работает
Krab Bark Искусственный Интеллект (284165) 1 месяц назад
#include <iostream>
#include <iomanip>
#include <ctime>
#include <cstdlib>
#include <vector>
using namespace std;
bool f(vector<vector<int>> &a,int &s){
s=0; bool b=false;
for(auto &i:a)for(auto &j:i)if(j%5==0&&j%2)s+=j,b=true;
return b;}
int main(){
size_t n,m; int s; cout<<"N M: "; cin>>n>>m; srand(time(NULL));
vector<vector<int>> a(n, vector<int>(m));
for(auto &i:a){for(auto &j:i)
cout<<setw(4)<<(j=rand()%100); cout<<endl;}
if(f(a,s))cout<<s; else cout<<"none"; cout<<endl;}
CPT Просветленный (21398) 1 месяц назад
 #include  
using namespace std;

bool sum_of_elements(int arr[][1000], int n, int m, int& sum) {
bool has_element = false;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (arr[i][j] % 5 == 0 && arr[i][j] % 2 != 0) {
sum += arr[i][j];
has_element = true;
}
}
}
return has_element;
}

int main() {
int n, m;
cout << "Введите размерность массива: ";
cin >> n >> m;
int arr[1000][1000];
cout << "Введите элементы массива: " << endl;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
cin >> arr[i][j];
}
}
int sum = 0;
bool has_element = sum_of_elements(arr, n, m, sum);
cout << "Сумма элементов массива кратных 5 и не кратных 2: " << sum << endl;
cout << "Есть ли элементы массива кратные 5 и не кратные 2? " << (has_element ? "Да" : "Нет") << endl;
return 0;
}
Похожие вопросы