本帖最后由 xwh 于 2018-10-30 22:17 编辑
Background Unless you are reading a research paper in engineering or computer science, when people write "random number" with regards to computers, they really mean "pseudorandom number". The basic problem is that if you start from a single value (known as the random seed), and do a series of mathematical operations on it, you will not get an actual random number -- every time you start from the same random seed, you will get the same number!
To quote one of the giants in computer science,
"Anyone who attempts to generate random numbers by deterministic means is, of course, living in a state of sin." - John von Neumann
However, pseudorandom numbers are good enough for this course.
Technical details Generating a random number: getRand() requires extra #include files!
- #include <stdio.h>
- #include <stdlib.h> // extra includes!
- #include <time.h> /* Get a random number from 0 to 0.9999999 (
- you don't need to understand this function)
- ***** DON'T MODIFY THIS FUNCTION ***** */
- float getRand() {
- return rand() / (RAND_MAX+1.0);
- }
- int main() {
- srand( time(NULL) ); // init random
- getRand(); // kick-start the random numbers
- float number = getRand();
- printf("Random number: %f\n", number);
- getchar();
- }
-
复制代码 Your task... Write a "dice rolling" game. You are probably familiar with 6-sided dice, but some games use dice with 4, 6, 8, 10, 20, and 100 sides!
• Make the computer pick a random number for a 6-sided die and a 20-sided die.
• Use the getRand() function, but do not modify it.
• Write an int rollDie(...) function to get a random value. o have one integer argument for the value of the die (int number_of_sides), o call the getRand() function. o take the value it returns (a float between 0 and 0.999...) and do some math to transform that into an int between 1 and number_of_sides inclusive). o return the number.
• Your int main() must contain only:
- int main() {
- srand(time(NULL));
- getRand();
- int value = 0;
- value = rollDie(6);
- printf("6-sided die: %i\n", value);
- value = rollDie(20);
- printf("20-sided die: %i\n", value);
- getchar();
- }
复制代码
|