C/C++

Задача на языке С++.

Дан массив целых чисел A. Найти суммы положительных и отрицательных элементов массива, используя функцию определения суммы
#include <algorithm>
#include <iostream>
#include <random>
#include <iomanip>
#include <numeric>
using namespace std;
int main() {
uniform_int_distribution<> uid(-9, 9);
mt19937 gen{ random_device()() };
const auto rand = [&] { return uid(gen); };
const auto show = [](int x) { cout << setw(4) << x; };
const auto pos = [](int s, int n) { return n > 0? s + n : s; };
const auto neg = [](int s, int n) { return n < 0? s + n : s; };
int a[10];
generate(begin(a), end(a), rand);
for_each(begin(a), end(a), show);
puts("");
auto sum_pos = accumulate(begin(a), end(a), 0, pos);
auto sum_neg = accumulate(begin(a), end(a), 0, neg);
system("chcp 1251 > nul");
cout
<< "Сумма положительных: " << sum_pos << '\n'
<< "Сумма отрицательных: " << sum_neg << '\n';
system("pause > nul");
}
Руслан Саттаров
Руслан Саттаров
85 904
Лучший ответ
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include<unistd.h>
long int Sum(int *arr,int N,char *type)
{
long int sum=0;
if(type=="plus"||type=="+")
{
for(int i=0; i=0) sum+=*arr++;
arr++;
}
}
else if(type=="minus"||type=="-")
{
for(int i=0; i<N; i++)
{
if(*arr<0) sum+=*arr;
arr++;
}
}
else sum=-1;
arr-=N;
return sum;
}

int main()
{
int N, *arr;
printf("Enter dimension of array N = ");
scanf("%d",&N);
arr=(int*)malloc(N*sizeof(int));
if(arr)
{ //if arr
srand(time(NULL));
printf("\n\nArray of digits:\n");
for(int i=0; i<N; i++)
{
if(rand()%2==0)
*arr=(-1)*rand()%100;
else *arr=rand()%100;
printf("%d ",*arr);
arr++;
}
arr-=N;
printf("\n\nPlus-sum is %ld",Sum(arr,N,"+"));
printf("\n\nMinus-sum is %ld\n\n",Sum(arr,N,"-"));

free(arr);
}//if arr
fflush(stdout);
sleep(10);
return 0;
}
ТМ
Титов Михаил
37 945