如何在c ++中生æˆéšæœºæ•°

时间:2015-04-24 11:38:36

标签: c++ random

#include<iostream>
using namespace std;
#include<stdlib.h>

int main()
{
  cout<<rand();
}

当我è¿è¡Œè¿™ä¸ªç¨‹åºæ—¶ï¼Œå®ƒä¼šç”Ÿæˆåƒ41这样的éšæœºæ•°ã€‚当我å†æ¬¡è¿è¡Œç¨‹åºæ—¶ï¼Œå®ƒä¼šç”Ÿæˆç›¸åŒçš„数字,å³41。

但是我想在è¿è¡Œç¨‹åºæ—¶å§‹ç»ˆç”Ÿæˆä¸åŒçš„éšæœºæ•°ã€‚那么,请告诉我,怎么åšï¼Ÿ

2 个答案:

答案 0 :(得分:0)

此示例代ç ä½¿ç”¨ç³»ç»Ÿæ—¶é—´ä½œä¸ºç§å­å¹¶ä½¿ç”¨rand函数生æˆéšæœºæ•°ï¼Œå› æ­¤æ¯æ¬¡è¿è¡Œæ­¤ä»£ç æ—¶ï¼Œæ‚¨å°†èŽ·å¾—ä¸åŒçš„   éšæœºæ•°

#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;
int main()
{
  time_t t;
    /*get the system time*/
    time(&t);
    /*transfer time_t variable to integer variable and send it to the srand function*/
    srand((unsigned int) t);
    /*Generating 10 random numbers continuous*/
    for (int i = 0; i < 10; i++)
        cout<<"The random number is "<<rand()<<endl;
    cin.get();
    return 0;

}

答案 1 :(得分:0)

å°è¯•ä½¿éšæœºç§å­åˆå§‹åŒ–:

/* initialize random seed: */
  srand (time(NULL));

http://www.cplusplus.com/reference/cstdlib/rand/