简体   繁体   English

在 C 中播种 rand() 并指定值

[英]Seeding rand() in C with Specified Values

If you wanted a random number generator to use ints 2,5,7,4 and you seed your generator with如果您希望随机数生成器使用整数 2、5、7、4,并且您使用

srand(2,5,7,4)

printf("%d \n",rand())

Is this flawed in accomplishing that?这样做有缺陷吗?

That is not how it works.这不是它的工作方式。 An PRNG uses an algorithm to generate a sequence of numbers with random like behaviour. PRNG 使用一种算法来生成具有随机行为的数字序列。 For a given seed, a given sequence of numbers will be generated, what those number are is entirely up to the algorithm used.对于给定的种子,将生成给定的数字序列,这些数字是多少完全取决于所使用的算法。

to get a random number for a list, you will need something like:要获取列表的随机数,您将需要以下内容:

n = list[rand() % (sizeof(list) / sizeof(list[0])];

In case you want to print a value from a given array randomly on each execution, you may consider using the following:如果您想在每次执行时从给定数组中随机打印一个值,您可以考虑使用以下内容:

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

int main() {
    srand ( time(NULL) ); // accepts one argument only

    int myArray[4] = { 2,5,7,4 }; // array required
    int randomIndex = rand() % 4; // limiting randomness
    int randomValue = myArray[randomIndex]; // choosing one of the random numbers

    printf("Random value from array: %d\n", randomValue); // simply prints
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM