for the program i need a function that displays a histogram showing the numbers (that the user has given using a vector) in each 5 five unit range (i.e. 1-5,6-10
How do you make a C++ histogram?
The trick to this is using the proper coding structure... a switch statement. A histogram is basically a bar chart that shows relative frequencies (total counts for a given value... how many fives, how many eights etc) so that you can see a distribution of values.
int firstrange = 0;
int secondrange = 0;
int thirdrange = 0;
int howmanyunknowns = 0;
for(int i=0;i %26lt; int_Vector.size(); i++)
{
int d = int_Vector.at(i);
switch (d) {
case 1:
case 2:
case 3:
firstrange++;
break;
case 4:
case 5:
case 6:
secondrange++;
break;
case 7:
case 8:
case 9:
thirdrange++;
break;
default:
howmanyunknowns++;
}
}
The above loop would run through a integer vector looking for 1's, 2's, 3's...etc and count them up, placing them in the correct range variable counter. (Values of 1, 2, 3 go into one variable... firstrange)
At the end you would have a count of each range for displaying as you like.
Granted this switch statement can only handle a limited set of ranges, but if you need more and bigger ranges, remember you can write a switch statement into a series of if statements...
if ((x %26gt;=1) %26amp;%26amp; (x %26lt;= 20)) { firstrange++; }
if ((x %26gt;=21) %26amp;%26amp; (x %26lt;= 40)) { secondrange++; }
etc etc etc.
Side Note: You could use a vector iterator instead of a for loop. I just used one to make it a bit more simple looking.
Hope you get the idea.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment