1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
|
#include <string>
#include <cctype>
#include <iostream>
#include <fstream>
#include <cmath>
#include <iomanip>
using namespace std;
const int ANTAL_BOKSTAVER = 26; //A-Z
void berakna_histogram_abs(string &rad, int frekvens[], double &antal);
void abs_till_rel(double rel_frekvens[], int frekvens[], double &antal);
void plotta_histogram (double rel_frekvens[]);
int main()
{
string rad;
int frekvens[ANTAL_BOKSTAVER];
double antal;
double rel_frekvens[ANTAL_BOKSTAVER];
cout << "Ge en rad med text:" << endl;
getline(cin,rad);
berakna_histogram_abs(rad, frekvens, antal);
abs_till_rel(rel_frekvens, frekvens, antal);
plotta_histogram(rel_frekvens);
return 0;
}
void berakna_histogram_abs(string &rad, int frekvens[], double &antal)
{
for (int i=0; i<ANTAL_BOKSTAVER; i++)
frekvens[i] = 0;
for (int i=0; i< (int) rad.length(); i++)
{
int index;
if (rad.at(i)>='a' && rad.at(i)<='z')
{
index = rad.at(i) - 'a'; frekvens[index]++;
antal++;
}
if (rad.at(i)>='A' && rad.at(i)<='Z')
{
index = rad.at(i) - 'A'; frekvens[index]++;
antal++;
}
}
}
void abs_till_rel(double rel_frekvens[], int frekvens[], double &antal)
{
for (int i=0; i<ANTAL_BOKSTAVER; i++)
rel_frekvens[i] = frekvens[i]/antal*100;
}
void plotta_histogram_rel (double rel_frekvens[])
{
char bokstav;
string asterisk="*";
string plott;
bokstav='A';
for (int i=0; i<ANTAL_BOKSTAVER; i++)
{
for (int j=0; j<rel_frekvens[i]; j++)
{
plott.append(asterisk);
}
cout << bokstav << setw(8) << plott << endl;
}
}
|