Oct 17, 2012 at 5:05pm UTC
i am writing a histogram and i am almost done i just need help with the final format of the astericks:
The longest bar always should contain 50 asterisks, and the other bars should be scaled proportionally. The sample input
450 401 3 78 444 200 -1
should look like:
0- 99 2|*********************************
100-199 0|
200-299 1|*****************
300-399 0|
400-499 3|**************************************************
500+ 0|
here is my code:
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
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
int a=0,b=0,c=0,d=0,e=0,f=0,i=0;
while (cin>>i)
{
if (i>0 && i<100)
a++;
else if (i>=100 && i<200)
b++;
else if (i>=200 && i<300)
c++;
else if (i>=300 && i<400)
d++;
else if (i>=400 && i<500)
e++;
else if (i>=500)
f++;
else
if (i == -1 )
break ;
}
cout << setw (7) << "0-99" << setw (4) << a << "|" ;
for (int i=0;i<a;i++)
cout <<"*" ;
cout<< endl;
cout << setw (5) << "100-199" << setw (4) << b << "|" ;
for (int i=0;i<b;i++)
cout <<"*" ;
cout<< endl;
cout << setw (5) << "200-299" << setw (4) << c << "|" ;
for (int i=0;i<c;i++)
cout <<"*" ;
cout<< endl;
cout << setw (5) << "300-399" << setw (4) << d << "|" ;
for (int i=0;i<d;i++)
cout <<"*" ;
cout<< endl;
cout << setw (5) << "400-499" << setw (4) << e << "|" ;
for (int i=0;i<e;i++)
cout <<"*" ;
cout<< endl;
cout << setw (6) << "500+" << setw (5) << f << "|" ;
for (int i=0;i<f;i++)
cout <<"*" ;
cout<< endl;
}
how should i do that??
Last edited on Oct 17, 2012 at 5:11pm UTC
Oct 17, 2012 at 5:43pm UTC
You need to find the maximum value of a through f.
Then adjust the scale of the histogram by a factor of 50/max. i.e. change the number of asterisks printed by that factor.
Oct 17, 2012 at 5:48pm UTC
i dont really know how to find the max of those numbers. do i need and array of some sort?
Oct 17, 2012 at 5:59pm UTC
An array would be good if you had many values to deal with.
For just six, you can simply code it line by line.
First, declare an integer called max, and set it equal to a.
Then compare it with each of the other values, like this,
if (b>max) max = b;
and do the same for c through f.
Last edited on Oct 17, 2012 at 6:00pm UTC
Oct 17, 2012 at 6:30pm UTC
ok thanks i got that down but the scale of the histogram part still is knda confusing
Oct 17, 2012 at 6:40pm UTC
oh ok i was trying to repalce a with 50/max for some reason
thanks alot