我的随机数生成器函数生成相同的数字

时间:2013-11-23 05:13:31

标签: c

如何让我的addRandomNumbers()函数为数组添加不同的数字?现在它只是添加相同的数字。

我不知道我做错了什么,我原来在for循环之外,它仍然生成了相同的数字。

#include <stdio.h>
#include <stdlib.h>
#include <time.h> 

#define clear       system("cls") 
#define pause       system("pause") 
#define SIZE        5000
#define LB          1    //this is the lower bound
#define UB          500  //this is the upper bound


//Lets Prototype
void addRandomNumbers(int n[]);
void bubbleSort(int n[]);
void displayRandomNumbers(int n[],int c[]);

int main(){
    int numbers[SIZE]={0}, counter[SIZE]={0};

    addRandomNumbers(numbers);
    bubbleSort(numbers);
    displayRandomNumbers(numbers,counter);

}

void addRandomNumbers(int n[]){
    int i;

    for (i=0; i < SIZE; i++){
        srand((unsigned)time(NULL));//seed the random number function
        n[i] = LB + rand() % (UB - LB + 1 );
    }
}

void bubbleSort(int n[]){
    int i,temp=0;
    for(i=0;i<SIZE-1;i++){
        temp=n[i];
        n[0]=n[1];
        n[i+1]=temp;
    }
}

void displayRandomNumbers(int n[], int c[]){
    int i;
    for(i=0;i<LB;i++)
        printf("It is %i\n",n[i]);
    pause;
}

3 个答案:

答案 0 :(得分:1)

如果您使用时间为随机数生成器播种,它将重复相同的数字,直到时间变​​化需要1秒。不要这样做 - 在程序开始时只将生成器播种一次。

答案 1 :(得分:1)

仅在程序开头调用srand一次。

答案 2 :(得分:1)

你试过吗

srand(time(NULL));
int r = rand();
相关问题