Monday, July 27, 2009

C/C++ question?

What's the syntax to generate a random number?

C/C++ question?
a brief introduction to the random number functions that come as part of the C++ standard library, namely rand() and srand().





rand() and RAND_MAX





The C++ standard library includes a pseudo random number generator for generating random numbers. In order to use it we need to include the %26lt;cstdlib%26gt; header. To generate a random number we use the rand() function. This will produce a result in the range 0 to RAND_MAX, where RAND_MAX is a constant defined by the implementation.





Here's a piece of code that will generate a single random number:





#include %26lt;cstdlib%26gt;


#include %26lt;iostream%26gt;





using namespace std;





int main()


{


int random_integer = rand();


cout %26lt;%26lt; random_integer %26lt;%26lt; endl;


}





The value of RAND_MAX varies between compilers and can be as low as 32767, which would give a range from 0 to 32767 for rand(). To find out the value of RAND_MAX for your compiler run the following small piece of code:





#include %26lt;cstdlib%26gt;


#include %26lt;iostream%26gt;





using namespace std;





int main()


{


cout %26lt;%26lt; "The value of RAND_MAX is " %26lt;%26lt; RAND_MAX %26lt;%26lt; endl;


}





srand()





The pseudo random number generator produces a sequence of numbers that gives the appearance of being random, when in fact the sequence will eventually repeat and is predictable.








So forth...visit


http://www.daniweb.com/forums/post9554.h...














Hope this will help


Cheers:)
Reply:Generating Random Numbers


The function used to generate random numbers is;





int random (int n);





which generates a random number in the range of 0 to n-1. For example;








y = random(100);





y will be in the range of 0 though 99.





In order to avoid repetition, you may seed it with linking with the real time clock which then will give random numbers.





Youj may use to program shown in link :


http://www.phanderson.com/C/random.html
Reply:She said C/C++ foxcon....





You can use rand() or srand().





#include %26lt;cstdlib%26gt;


#include %26lt;iostream%26gt;





using namespace std;





int main()


{


int random_integer = rand();


cout %26lt;%26lt; random_integer %26lt;%26lt; endl;


}
Reply:Don't bother your pretty little head about it.
Reply:http://www.jsifaq.com/SF/Tips/Tip.aspx?i...





http://www.supelec.fr/docs/cltl/clm/node...





http://www.dummies.com/WileyCDA/DummiesA...
Reply:in c


this will print random number from 1 to 10


#include %26lt;stdlib.h%26gt;


#include %26lt;stdio.h%26gt;


#include %26lt;conio.h%26gt;


int main(void)


{


randomize();


printf("%d", rand()%10+1)


getch();


return 0;


}


No comments:

Post a Comment