C++ Bc. 5 cpp

Z GeoWikiCZ
#include <iostream>
#include <sstream> // istringstream
#include <list>
#include <vector>
#include <iomanip> // manipulatory datoveho proudu

void histogram(const std::list<double>& data, double min, double max, int N,
               std::vector<double>& hist);

int main ()
{
  using namespace std;

  istringstream input ("1.64 3.84 5.93 7.98 9.54 6.98 4.99 3.28 2.25 2.13 "
		       "4.58 6.60 7.72 8.88 8.56 5.47 3.59 7.43 4.31 4.68 "
		       "6.10 6.43 5.43 5.33 5.69");

  const double min = 2.0;
  const double max = 9;
  const int    N   = 7;

  list<double>   data;
  vector<double> hist;

  // nacist vstupni data do kontejneru 'data'
  double hodnota;
  while (input >> hodnota)
    {
      data.push_back (hodnota);
    }

  histogram (data, min, max, N, hist);

  // vypsat histogram
  cout.setf (ios_base::fixed, ios_base::floatfield);
  
  const double delta = (max - min) / N;

  for (int i = 0; i < hist.size (); i++)
    {
      stringstream interval;
      interval.setf (cout.flags());
      
      interval.precision (1);
      if (i != 0 && i != (hist.size() - 1))
	{
	  interval << (min + (i - 1) * delta) << "-" << min + i * delta;
	}
      else
	{
	  if (i == 0)
	    {
	      interval << "<" << min;
	    }
	  else
	    {
	      interval << ">" <<  max;
	    }
	}

      cout << setw (11) << interval.str();

      cout.precision (2);
      cout << setw (8) << hist[i] / data.size () * 1e2 << endl;
    }

  return 0;
}
 
void histogram(const std::list<double>& data, double min, double max, int N,
               std::vector<double>& hist) {

  const double delta = (max - min) / N;

  hist.resize (N+2);

  for (std::list<double>::const_iterator i = data.begin (), e = data.end ();
       i != e; ++i)
    {
      if ((*i) < min)
	{
	  hist[0]++;
	  continue;
	}

      if ((*i) >= max)
	{
	  hist[N+1]++;
	  continue;
	}

      for (int in = 0; in < N; in++)
	{
	  if ((*i) >= (min + in * delta) && (*i) < (min + (in + 1) * delta))
	    {
	      hist[in+1]++;
	      break;
	    }
	}
    }

  return;
}

[ Zpět ]