Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

97 строки
2.0 KiB
C++

#include <iostream>
#include <vector>
using namespace std;
const size_t SCREEN_WIDTH = 80;
const size_t MAX_ASTERISK = SCREEN_WIDTH - 6 - 1;
struct Input {
vector<double> numbers;
size_t bin_count{};
};
Input
input_data(){
size_t number_count;
cin >> number_count;
Input in;
in.numbers.resize(number_count);
for (size_t i = 0; i < number_count; i++){
cin >> in.numbers[i];
}
cin >> in.bin_count;
return in;
}
void
find_minmax(const vector<double>& numbers, double& min, double& max){
min = numbers[0];
max = numbers[0];
for (double x: numbers){
if (min > x){
min = x;
}
if (max < x){
max = x;
}
}
}
vector<size_t> make_histogram(const vector<double>& numbers, size_t bin_count){
double min, max;
vector <size_t> bins(bin_count);
find_minmax(numbers, min, max);
double diff = (max - min) / bin_count;
size_t max_count = 0;
for (double x: numbers){
bool found = false;
for (size_t j = 0;(j < bin_count - 1) && !found; j++){
auto lo = min + j * diff;
auto hi = min + (j + 1) * diff;
if ((lo <= x) && (hi > x)){
bins[j]++;
found = true;
}
}
if(!found){
bins[bin_count - 1]++;
if (bins[bin_count - 1] > max_count){
max_count = bins[bin_count - 1];
}
}
}
return bins;
}
void show_histogram_text(const vector<size_t>& bins){
for (double x: bins){
cout << " ";
if (x < 100){
cout << " ";
}
if (x < 10){
cout << " ";
}
cout << x << "|";
size_t number_of_stars = x;
for (size_t j = 0; j < number_of_stars; j++){
cout << "*";
}
cout << endl;
}
}
int main(){
auto in = input_data();
auto bins = make_histogram(in.numbers, in.bin_count);
show_histogram_text(bins);
}