Sunday, July 12, 2009

How can i use random in C if I am using strings?

i am making a program in C., and it is about the card game black jack, how can i randomize the cards? what functions will i use? please help.

How can i use random in C if I am using strings?
Ok, there are two implortant things here - the random function in C isn't actually random - it will give you the same sequence of random numbers each time a program is run. To solve this you need to use a unique 'seed' which is a number that the the random number function uses to generate random numbers.


If you use the current time it will be different every time:


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


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


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





int main()


{





int i;


srand( (unsigned)time( NULL ) );





for (i = 0; i %26lt; 5; i++) {


printf("%d\n",rand());


}





return 0;


}





As for getting a random card, the modulus operator (%) should be helpful here.


Assign a number to each card (A-1, 2-2.... J-11, )


Then use then do something like:





(int)((100*rand())%13+1);


to get a random number between 1 and 13 (inclusive)





Hope this helps


No comments:

Post a Comment