944,050 Members | Top Members by Rank

Ad:
  • C++ Discussion Thread
  • Unsolved
  • Views: 2341
  • C++ RSS
Apr 12th, 2007
0

Generating random numbers using VC6

Expand Post »
Hi , im trying to create a simple code that generate random numbers
Im having two problem ,
1. For some reason randomize() function does not work on VisualC++6
2. I didnt really got the idea on how to set the range of the numbers that will be generated using the rand() function ,. i just saw it in some example .

Here is the code:
C++ Syntax (Toggle Plain Text)
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. int main()
  4. {
  5. int i;
  6. randomize();
  7. for (i=0;i<10;i++)
  8. printf ("Number %d: %d\n",i+1,rand()%10+1);
  9. return 0;
  10. }
Last edited by RisTar; Apr 12th, 2007 at 8:24 am.
Similar Threads
Reputation Points: 10
Solved Threads: 1
Junior Poster in Training
RisTar is offline Offline
51 posts
since Feb 2007
Apr 12th, 2007
0

Re: Generating random numbers using VC6

hey,
i will like you to try this for C, i use VC6 but the program is C++ and i get my random numbers anytime i want....

first include this
C++ Syntax (Toggle Plain Text)
  1. #include <cstdlib>
  2. using std::rand;

after that.. whenever you want to generate the random numbers,

C++ Syntax (Toggle Plain Text)
  1.  
  2. rand()%4

wil generate one of 0, 1, 2, 3;

now if you want the number to be in the range 1 to 4, just use the code
C++ Syntax (Toggle Plain Text)
  1.  
  2. 1 + rand()%4;

now you will get number in the range 1,2,3,4;

note 1 is the smallest and 4 is the largest;

if you want to generate the numbers 2, 4, 6, 8...
its by doing the same but adding 2 instead

C++ Syntax (Toggle Plain Text)
  1.  
  2. 2 + rand()%4;
Last edited by addicted; Apr 12th, 2007 at 11:46 am. Reason: the code was for c++
Reputation Points: 10
Solved Threads: 0
Junior Poster in Training
addicted is offline Offline
57 posts
since Mar 2007
Apr 12th, 2007
0

Re: Generating random numbers using VC6

Click to Expand / Collapse  Quote originally posted by RisTar ...
1. For some reason randomize() function does not work on VisualC++6
That's because this is C++, not Basic. You 'randomize' using srand(time()); once at the start of the program. Be sure to include time.h
Moderator
Reputation Points: 3278
Solved Threads: 894
Posting Sage
WaltP is offline Offline
7,747 posts
since May 2006

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in C++ Forum Timeline: Borland C++
Next Thread in C++ Forum Timeline: Implementation file





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC