Sunday, May 10, 2009

Can someone help me how to code a random number in Turbo C?, like a random selection in numbers 1,2 and 3.?

cause im doing a game in Turbo C which is rocks-papers-scissors but it's against a computer player, that's why i need to make it random for the computer's choice, for example 1=paper, 2=scissors, and 3=rocks.

Can someone help me how to code a random number in Turbo C?, like a random selection in numbers 1,2 and 3.?
Since there are 3 elements in the array, need to generate a random number between 0 and 2. Let me note, I haven't done this in Turbo C, but I have done it in Dev-C++, both in C++ and normal C.





If doing it in C, you will need the header file: time.h


So it's be: #include %26lt;time.h%26gt;





In C++, you don't need to use that header file. Using the standard namespace will do fine.





From here on, generating the number is same in both languages.





First, you need to know something. Computers can't generate TRULY random numbers. It uses a long algorithm to create a number which seems random. But if you run the application again, it'll generate the same random numbers all over again. To get around this, we need to "plant" a variable into the generation algorithm, calle "seeding". Most common thing to seed it with is the System Time.





Like so: srand(time(NULL));





Remember, you need to have that ^ statement BEFORE you begin generating numbers. This should make them more random.





From there, you need to generate random numbers. When you generate a random number, it'll be between 0 and 32767 (depends on the system I guess). To get it down to within a small range from 0 to n, we need to do some modular division.





Modular division (in case you don't know), is dividing a number and returning the remainder. Since we want the number to be between 0 and 2, we need to do:





{RANDOM NUMBER} % 3. This will always result in a 0, 1, or 2.





From here, it's easy. To generate a random number (between 0 and 32676) use RAND().





int randomNumber = rand() % 3;





That ^ statement above will generate a number between 0 and 2, which can then be used directly as an index for your array.





Hope my explanations were adequate.
Reply:There are functions for generating random numbers like rand();





Observe the following code and see how random numbers are generated





/* rand example: guess the number */


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


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


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





int main ()


{


int iSecret, iGuess;





/* initialize random seed: */


srand ( time(NULL) );





/* generate secret number: */


iSecret = rand() % 10 + 1;





do {


printf ("Guess the number (1 to 10): ");


scanf ("%d",%26amp;iGuess);


if (iSecret%26lt;iGuess) puts ("The secret number is lower");


else if (iSecret%26gt;iGuess) puts ("The secret number is higher");


} while (iSecret!=iGuess);





puts ("Congratulations!");


return 0;


}


No comments:

Post a Comment