Вопрос Составить программу в с++, разбив каждый этап на функции.

Регистрация
29 Окт 2012
Сообщения
158
Репутация
0
Спасибо
0
Монет
0
Задание:



В одномерном массиве найти среднее арифметическое для элементов,

расположенных между максимальным и минимальным. Если они следуют один за

другим, считать его равным нулю. Количество элементов в массиве не более 200.

Формат числа цц.ц. Массив распечатывать по десять элементов на строке.



Массив, минимум и максимум и среднее арифметическое нужно оформить как отдельные функции, вне int main().



Преподаватель требует, не объяснив ни слова, как это сделать, я в отчаянии.

Прошу, помогите!
 
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>

using namespace std;

const int N = 200;

double arr[N];

double findMin(double arr[], int size)
{
// Find the minimum element in the array
double min = arr[0];
for (int i = 1; i < size; i++)
min = min(min, arr);
return min;
}

double findMax(double arr[], int size)
{
// Find the maximum element in the array
double max = arr[0];
for (int i = 1; i < size; i++)
max = max(max, arr);
return max;
}

double mean(double arr[], int size, double min, double max)
{
// Find the arithmetic mean of the elements between min and max in the array
double sum = 0;
int count = 0;
for (int i = 0; i < size; i++)
{
if (arr > min && arr < max)
{
sum += arr;
count++;
}
}
return (count == 0) ? 0 : sum / count;
}

int main()
{
int size;
cout << "Enter the size of the array: ";
cin >> size;

cout << "Enter the elements of the array: ";
for (int i = 0; i < size; i++)
cin >> arr;

double min = findMin(arr, size);
double max = findMax(arr, size);
double m = mean(arr, size, min, max);

cout << "Minimum element: " << min << endl;
cout << "Maximum element: " << max << endl;
cout << "Arithmetic mean: " << m << endl;

return 0;
}
 
#include "iostream"
#include "numeric"
#include "ctime"
#include "cstdlib"
#include "algorithm"
using namespace std;
void arrgen(float *a, int n){srand(time(NULL)); for(int i=0;i<n;i++)a=rand()%1000/10.;}
void arrprn(float *a, int n){for(int i=0;i<n;i++){cout<<a<<'\t'; if(i%10==9)cout<<endl;}}
float* max(float *a, int n){return max_element(a,a+n);}
float* min(float *a, int n){return min_element(a,a+n);}
float av(float *a,float *i,float *j){if(j>i)swap(i,j); int m=i-j-1;
return m?accumulate(j+1,i,0.)/m:0.;}
int main(){
int n; cout<<"N: "; cin>>n; float *a=new float[n],s; arrgen(a,n); arrprn(a,n);
float *i=max(a,n), *j=min(a,n); cout<<endl; cout<<"\nav="<<av(a,i,j)<<endl;}
 
1) Создается функция void в которой определяются int min, int max, int avg.
2) В этой функции прописывается логика

Логику такой сложной программы проще писать вложенными циклами (for i++ внутри которого for j++ (важно чтобы эти переменные отличались). Путём перебора и сравнения каждого можно получить наименьшее и наиболее. Среднее арифм. считать учат ещё в начальной школе, пояснять не буду.

3) В главной функции int main
Задается массив, можно сразу ограничить его до 200 элементов или сделать динамический (по опыту правильно написать с 1 раза динамический массив могут единицы людей). Запись в массив делается в цикле. Далее идёт обращение к функции void. покажу на примере: #include "stdafx.h"
#include
using namespace std;

// объявление функции нахождения n!
void faktorial(int numb)// заголовок функции
{
int rezult = 1; // инициализируем переменную rezult значением 1
for (int i = 1; i
 
#include
#include
#include

#define RAND(min, max) (rand() % ((max) - (min)) + (min))

using namespace std;

size_t min_element(
double* box,
const size_t n
) {
size_t min = 0;
for (size_t i = 1; i < n; ++i) {
if (box < box[min]) {
min = i;
}
}
return min;
}

size_t max_element(
double* box,
const size_t n
) {
size_t max = 0;
for (size_t i = 1; i < n; ++i) {
if (box[max] < box) {
max = i;
}
}
return max;
}

size_t input(
const char* msg,
const size_t limit
) {
size_t value = 0;
while (!value || value > limit) {
cout > value;
cin.ignore(0x1000, '\n');
}
return value;
}

void random_fill(
double* box,
const size_t n
) {
srand(unsigned(time(nullptr)));
for (size_t i = 0; i < n; ++i) {
box = RAND(100, 1000) / 10.0;
}
}

void show(
double* box,
const size_t n,
const streamsize p,
const streamsize w,
const size_t lf
) {
cout
 
Назад
Сверху