program needs to ask the user to input the num of numbers they want to store in a vector, %26amp; print out the smallest num, the largest, %26amp; the average. this is my code but i get vector subscript out of range %26amp; i dont know wat to do
#include %26lt;iostream%26gt;
#include %26lt;vector%26gt;
using namespace std;
int main ()
{
int numloop, value, small, large;
int sum=0;
double avg;
vector %26lt;int%26gt; vectorlist;
cout%26lt;%26lt;"Please enter the total number of numbers to be stored:"%26lt;%26lt;endl;
cin%26gt;%26gt;numloop;
for(int i=0; i%26lt;numloop; i++)
{
cout%26lt;%26lt;"Please enter value to be stored:"%26lt;%26lt;endl;
cin%26gt;%26gt;value;
vectorlist.push_back(value);
}
small=vectorlist[0];
for (int i=1; i%26lt;=numloop; i++)
{
if(small%26gt;vectorlist[i])
small=vectorlist[i];
}
large=vectorlist[0];
for(int i=1; i%26lt;=numloop; i++)
{
if(large%26lt;vectorlist[i])
large=vectorlist[i];
}
for(int i=0; i%26lt;numloop; i++)
{
sum+=vectorlist[i];
}
avg=sum/numloop;
cout%26lt;%26lt;"Smallest number:"%26lt;%26lt;small%26lt;%26lt;endl;
cout%26lt;%26lt;"Largest number:"%26lt;%26lt;large%26lt;%26lt;endl;
return 0;
}
Can someone please help me with my c++ program?
instead of writing all that. declare the vector AFTER you get input for how many numbers to use
ie
cout%26lt;%26lt;"Please enter the total number of numbers to be stored:"%26lt;%26lt;endl;
cin%26gt;%26gt;num;
edit: (been a while since C++)
vector %26lt;int%26gt;vectorlist(num); %26lt;- thats how it should look.
edit: also make sure you arent trying to acces part of a vector thats out of its bound. i had that mistake once where i had a loop start at 1 and not 0 but it ended 1 after the last spot in teh vector.
also you didnt declare i.
okokok i got it:
#include %26lt;iostream%26gt;
#include %26lt;vector%26gt;
using namespace std;
int main ()
{
int num, value, small, large, i;
int sum=0;
double avg;
cout%26lt;%26lt;"Please enter the total number of numbers to be stored:"%26lt;%26lt;endl;
cin%26gt;%26gt;num;
vector %26lt;int%26gt;vectorlist(num);
for (i = 0; i %26lt; num; i++)
{
cout %26lt;%26lt; "enter number" %26lt;%26lt; endl;
cin %26gt;%26gt; value;
vectorlist[i] = value;
}
small=vectorlist[0];
for (int i=0; i%26lt;num; i++)
{
if(small%26gt;vectorlist[i])
small=vectorlist[i];
}
large=vectorlist[0];
for(int i=0; i%26lt;num; i++)
{
if(large%26lt;vectorlist[i])
large=vectorlist[i];
}
for(int i=0; i%26lt;num; i++)
{
sum+=vectorlist[i];
}
avg=sum/num;
cout%26lt;%26lt;"Smallest number:"%26lt;%26lt;small%26lt;%26lt;endl;
cout%26lt;%26lt;"Largest number:"%26lt;%26lt;large%26lt;%26lt;endl;
system("PAUSE");
return 0;
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment