C/C++

Программирование на с++

Найти среднее арифметическое тех элементов одномерного массива X, значения которых не превышают X1, включая и сам элемент X1
#include <algorithm>
#include <iostream>
#include <numeric>
#include <random>
using namespace std;
class Random {
mt19937 gen;
public:
Random() {
random_device device;
gen.seed(device());
}
int next(int a, int b) {
uniform_int_distribution<int> uid(a, b);
return uid(gen);
}
};
int integer(const char* msg) {
cout << msg;
int value;
cin >> value;
cin.ignore(cin.rdbuf()->in_avail());
return value;
}
int main() {
const auto x = integer("X1: ");
const auto a = x - 10;
const auto b = x + 10;
int box[20];
Random rand;
for (auto& x : box) x = rand.next(a, b);
for (auto x : box) cout << x << ' ';
puts("");
const auto cmp = [x](int n) { return n <= x; };
const auto n = count_if(begin(box), end(box), cmp);
const auto acc = [x](double s, int n) { return n <= x? s += n : s; };
const auto sum = accumulate(begin(box), end(box), 0.0, acc);
const auto avg = sum / n;
cout << "Average: " << avg << '\n';
system("pause > nul");
}
ВМ
Владимир М
55 097
Лучший ответ
Садыр Набиев Здравствуйте! А почему именно x-10?
#include <iostream>

using namespace std;

int main()
{
int X[] = {10,20,15,7,4,17,18,34,12,5};
int X1 = 15;
double srednee;
int sum = 0;
int count = 0;
for(int x = 0; x < 10; x++)
{
if(X[x] <= X1)
{
sum += X[x];
count++;
}
}
if (count)
{
srednee = (double) sum / (double) count;
cout << srednee << endl;
}
else
{
cout << "Нет таких значений." << endl;
}

return 0;
}
С целым рандомным динамическим массивом, размер n и диапазон [a; b] которого задаются с экрана:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std; int main() { int a, b, l,
m, n; double s; srand(time(NULL)); while (1)
{ m = 0; cout << "a b n » "; cin >> a >> b >> n;
s = 0; int *A = new int [n]; for (l = 0; l < n; l++)
{ A[l] = a + rand() % (b + 1 - a); if (A[l] <= A[0])
{ s += A[l]; m++; } } if (m) cout << s / m << endl;
else cout << "no elemens" << endl; delete [] A; } }