adding a bunch of random numbers

Please support our C++ advertiser: Programming Forums - DaniWeb Sister Site
Thread Solved

Join Date: Sep 2009
Posts: 6
Reputation: blahbla is an unknown quantity at this point 
Solved Threads: 0
blahbla blahbla is offline Offline
Newbie Poster

adding a bunch of random numbers

 
1
  #1
Sep 17th, 2009
hi i need some help with adding a bunch of random numbers.
i dont understand how to add them all.
heres the code:

  1. #include <iostream>
  2. #include <cmath>
  3. using namespace std;
  4. int main ()
  5. {
  6. int i,x;
  7. srand (time (NULL));
  8. for (i=1; i<=10; i++){
  9. x=rand()%10+1;
  10. cout<<x<<endl;
  11. }
  12. system ("pause");
  13. return 0;
  14. }

i wanna know how to add up all 10 random numbers generated from this.
thank you.
Reply With Quote Quick reply to this message  
Join Date: Aug 2009
Posts: 73
Reputation: dgr231 is on a distinguished road 
Solved Threads: 7
dgr231's Avatar
dgr231 dgr231 is offline Offline
Junior Poster in Training

Re: adding a bunch of random numbers

 
0
  #2
Sep 17th, 2009
Hi blahbla,

It seems to me that your best bet would be to create a new variable before you start your loop that you use to add all of your random numbers together. I would suggest doing the addition right before the end of your for loop so that every iteration of the loop ends by adding the new random number to the accumulation variable.

See compound operators for the correct usage:
http://www.cplusplus.com/doc/tutorial/operators/

-D
Reply With Quote Quick reply to this message  
Join Date: Aug 2005
Posts: 5,273
Reputation: iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold iamthwee is a splendid one to behold 
Solved Threads: 378
Featured Poster
iamthwee's Avatar
iamthwee iamthwee is offline Offline
Posting Expert

Re: adding a bunch of random numbers

 
0
  #3
Sep 17th, 2009
set a variable at the beginning then add them all up:

eg.
  1. int total = 0;
  2.  
  3. for ( int i = 0; i < 10; i++ )
  4. {
  5. total = total + i;
  6. }
  7.  
  8. cout << total;
Last edited by iamthwee; Sep 17th, 2009 at 5:14 pm.
*Voted best profile in the world*
Reply With Quote Quick reply to this message  
Join Date: Sep 2009
Posts: 6
Reputation: blahbla is an unknown quantity at this point 
Solved Threads: 0
blahbla blahbla is offline Offline
Newbie Poster

Re: adding a bunch of random numbers

 
0
  #4
Sep 17th, 2009
thank you to both of you for answering i understand it now.
Reply With Quote Quick reply to this message  
Reply

This thread has been marked solved.
Perhaps start a new thread instead?
Message:




Views: 591 | Replies: 3
Thread Tools Search this Thread



Tag cloud for C++
About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC