C++/Development/Random

Материал из C\C++ эксперт
Перейти к: навигация, поиск

Outputs 20 random numbers from 1 to 100.

<source lang="cpp">

  1. include <stdlib.h>
  2. include <iostream>
  3. include <iomanip>

using namespace std; int main() {

  unsigned int  i, seed;
  cout << "\nPlease type an integer between "
          "0 and 65535: ";
  cin >> seed;     // Reads an integer.
  srand( seed);    
                   
  cout << "\n\n            "
          "RANDOM NUMBERS\n\n";
  for( i = 1 ; i <= 20 ; ++i)
     cout << setw(20) << i << ". random number = " << setw(3) << (rand() % 100 + 1) << endl;
  return 0;

}


 </source>


Rand function

<source lang="cpp">

  1. include <iostream>
  2. include <cstdlib>

using namespace std; class Dice {

 int val;

public:

 void roll();

}; void Dice::roll() {

 val = (rand() % 6) + 1; // generate 1 through 6
 cout << val << endl;

} int main() {

 Dice one, two;
 one.roll(); 
 two.roll();
 one.roll(); 
 two.roll();
 one.roll(); 
 two.roll();
 return 0;

}


 </source>


Random by time

<source lang="cpp">

  1. include <iostream>
  2. include <ctime>

using namespace std; int main( void ) {

int i,j;
srand( (unsigned)time( NULL ) );
/* Display 10 numbers. */
for( i = 0;i < 10;i++ )
{
  j= rand();
  cout << j << endl;
    }

}


 </source>