编程论坛's Archiver

julian1209 发表于 2008-5-7 12:15

有個关于srand的问题

又两个小程序:
   第一个:#include <iostream>
#include "stdlib.h"
#include "time.h"
using namespace std;

int getrand(){
    srand(time(NULL));
    return rand()%1000+1;   
}

void main(){
    int t;
    cout<<"随机产生的20个数显示如下:"<<endl;
    for(int i=0;i<20;i++){
        t=getrand();
        cout<<t<<endl;
    }
}

  第二个:#include <iostream>
#include "stdlib.h"
#include "time.h"
using namespace std;

int getrand(){
   
    return rand()%1000+1;   
}

void main(){
    int t;
        srand(time(NULL));
    cout<<"随机产生的20个数显示如下:"<<endl;
    for(int i=0;i<20;i++){
        t=getrand();
        cout<<t<<endl;
    }
}

为什么第一个函数产生的随机数是一样的,而第二个不一样?
srand()放在main函数里面和放在其外面有什么区别吗?

newyj 发表于 2008-5-7 12:59

好象是在调用完 函数后  函数会释放掉
不知道 是不是这个

julian1209 发表于 2008-5-7 18:05

呵呵

還是沒明白

页: [1]

Powered by Discuz! Archiver 6.1.0  © 2001-2007 Comsenz Inc.