Simulation algorithm: Simulate the whole process, by changing the mathematical model of the various parameters, and then observe the change of these parameters caused by the process state changes.
Algorithmic thinking: Use random functions to simulate unpredictable situations that occur in nature. (Srand () and rand () function generate random numbers)
The simulation algorithm is the whole process of finishing the entire walk once, the topic how to describe, the program how to run. Example one:Guess numbersThe computer randomly generates a 1-100 integer, and the user guesses that each guess gives a different hint. Code:
#include <iostream> #include <stdlib.h> #include <time.h>using namespace Std;int main () { Srand ( Time (NULL)); int count=0; int num = rand ()%100 + 1; int guess; cout << "Please enter the number of guesses:"; Cin >> guess; do{ if (guess > num) { count++; cout << "You guessed the value is big \ n"; cout << "Please enter the number of guesses again:"; Cin >> guess; } else if (guess < num) { count++; cout << "You guessed the value is small \ n"; cout << "Please enter the number of guesses again:"; Cin >> guess; } } while (guess! = num); count++; cout << "I guessed it! \ n "; cout << "Total guessed" << count << "times \ n"; return 0;}
Operation Result:
Example two: Simulation Dice game by the user input the number of participants and dice, and then the computer randomly generated each dice points and then count each person's points.
Code:
#include <iostream> #include <stdlib.h> #include <time.h>using namespace std;void play (int n); void Play (int n) { int i,m=0,t=0; for (i=0; i<n; i++) { t=rand ()%6+1; m+=t; cout << "<< (i+1) <<" Dice in points: "<< t <<" \ n "; } cout << "Total" << m << "point \ n";} int main () { int people,numbers; do{ Srand (Time (NULL)); cout << "Please enter the number of participants:"; Cin >> People; if (people = = 0) break; cout << "Please enter the number of dice:"; CIN >> numbers; if (numbers = = 0) break; for (int i=0; i<people; i++) { cout << "<< (i+1) <<" Players roll the dice case: \ n "; Play (numbers); } } while (1); return 0;}
Operation Result:
Note:
C + + generates random numbers for use
1) provide a seed to Srand (), which is a unsigned int type;
2) call Rand (), which returns a random number (between 0 and Rand_max) based on the seed value provided to Srand ();
3) Call Rand () as many times as necessary to obtain a new random number without interruption;
4) Whenever possible, a new seed can be given to Srand () to further "Randomize" the output of rand ().
A general expression formula for generating a certain range of random numbers
To obtain a random integer [A, b], use (rand ()% (b-a)) + A;
To obtain a random integer [A, b], use (rand ()% (b-a+1)) + A;
To obtain a random integer (A, b], use (rand ()% (b-a)) + A + 1;
General formula: A + rand ()% n; where a is the starting value and N is the range of integers.
Simulation algorithm of data structure and algorithm C + + implementation