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

标签 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;
}

最佳答案

如果您将时间作为随机数生成器的种子,它将不断重复相同的数字,直到时间发生变化,这需要 1 秒。不要那样做 - 只在程序启动时为生成器播种一次。

关于c - 我的随机数生成器函数生成相同的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20158841/

相关文章:

c - 为什么这段代码可以在应该为空的时候从 stdin 中读取?

python - 从 c 中创建的结构中读取 python 中的结构

python - 逆向工程自动生成的 C?

c++ - 以下代码以意想不到的方式获取输入

c - 操纵指针指向的内容

c - 如何阅读这段C代码?考试准备

多个弱符号的后果(C 链接器)

c - 外部变量声明和定义

c - Unix - 如何获取域名的IP地址?

c - 快速 3D Lut 查找