#include <iostream>
#include <algorithm>
#include <string>
#include <sstream>
#include <cctype>
#include <cstdlib>
float mean_avg(std::uint32_t*, std::uint32_t*, std::size_t size);
std::size_t count_numbers(std::string &in){
return std::count(in.begin(), in.end(), ' ');
}
std::uint32_t* split(std::string&, char);
int main(){
std::string numbers="";
std::string input="";
std::size_t counter=20;
std::cout<<"Wprowadz liczby oddzielajac oddzielajac je enterem, lub konczac enterem.\n";
do{
std::getline(std::cin, input, '\n');
if(input.empty()) break;
if(std::count_if(input.begin(), input.end(), ::isdigit) != input.length()){
std::cerr<<"Nieprawidlowe wejscie. Mozesz wprowadzac tylko liczby.\n";
continue;
}
numbers+=input+=" ";
--counter;
}while(counter);
std::uint32_t* array = split(numbers, ' ');
if(array==nullptr){
std::cerr<<"Nie mozna utworzyc tablicy\n";
return 57665;
}
std::size_t tab_size = count_numbers(numbers);
std::uint32_t max = array[0];
std::uint32_t min = array[0];
for(std::size_t i=0;i<tab_size;++i){
if(array[i]>max) max = array[i];
if(array[i]<min) min = array[i];
}
std::uint32_t *min_pos = std::find(array, array+tab_size, min);
std::uint32_t *max_pos = std::find(array, array+tab_size, max);
std::cout<<mean_avg(min_pos, max_pos, labs(max_pos-min_pos));
delete[] array;
}
std::uint32_t* split(std::string &in, char delimiter){
if(in.empty()) return nullptr;
std::uint32_t *tab = new std::uint32_t[count_numbers(in)];
std::istringstream string_in(in);
std::size_t index = 0;
for(std::string token; std::getline(string_in, token, delimiter);){
std::uint32_t num;
try{
num = std::stoi(token);
}catch(std::out_of_range&){
return nullptr;
}
tab[index] = num;
++index;
}
return tab;
}
float mean_avg(std::uint32_t *beg, std::uint32_t *end, std::size_t size){
if(beg==nullptr||end==nullptr) return 0;
if(beg==end) return *beg;
float retval = 0;
while(beg!=end){
retval += (*beg);
beg++;
}
std::cout<<"--------------------------------\n";
std::cout<<retval<<" "<<size<<'\n';
std::cout<<retval/size<<'\n';
std::cout<<"--------------------------------\n";
return retval/size;
}
Nie piszę tego dla siebie. Zadanie brzmi: "
Napisz program, który oblicza średnią arytmetyczną elementów leżących pomiędzy
elementem minimalnym i maksymalnym w tablicy liczb całkowitych. Przyjmij, że
maksymalny rozmiar tablicy to 20. Zadanie należy rozwiązać w oparciu o wskaźniki.
Przykład 1: dla tablicy: 2 5 6 2 3 2 2 0 1 0
min = 0, jego indeks = 7
max = 6, jego indeks = 2
średnia arytmetyczna elementów: 6 2 3 2 2 0 jest równa 15/6 = 2.5."
I niby wszystko jest dobrze, max_pos i min_pos wskazują dobrze, etc., ale nie liczy mi 10, ostatniego elementu tablicy, chyba, że dodam jeden, ale nie rozumiem co to dodawanie jedynki mi daje (tzn. rozumiem, że dodaję +4 do adresu, ale nie wiem czemu muszę to zrobić).
Gdyby ktoś byłby w stanie mi pomóc byłby bardzo wdzięczny..
Z góry dziękuję i pozdrawiam.