1-20范围内的最大随机数

时间:2013-11-02 14:19:20

标签: c random numbers

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

int main()
{
    int n, i;

    srand(time(NULL));

    for(i = 1; i <= 19; i++)
        printf("%d \n", rand() * 21 / RAND_MAX);

    return 0;
}

代码有效。有点。它显示在控制台20&#34;随机&#34; 1-20之间的数字。比如1 19 6 8 18 6 8等等。有些数字或多或少重复。

我需要的是显示最大的数字。我是菜鸟所以保持简单。谢谢。

3 个答案:

答案 0 :(得分:4)

那是怎么回事:

int biggest = 0;

for(i = 1;i < 20; i++){
   int num = rand() * 21 / RAND_MAX;

   if (num > biggest){
      biggest = num;
   }

   printf("%d \n", num);
}

printf("Biggest: %d \n", biggest);

答案 1 :(得分:0)

试试这个

int biggest = 0, num;


for(i=0; i < 20; i++)
{   
    num = 1 + rand()%20; 
    if (biggest < num)
        biggest = num;  
}       
printf("%d \n", biggest);

答案 2 :(得分:0)

信不信由你,你可以使用一个随机数进行这样的订单统计。如果k是随机值的数量且每个值都在1..max_value范围内,则:

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

int main(void)
{
    int seed;
    /*
     * Grab a seed value from /dev/random to avoid time dependency
     * artifacts in the first generated rand() value when running
     * this multiple times in quick succession.
     */
    FILE *fp = fopen("/dev/random", "r");
    fread((char*)(&seed),sizeof(seed),1,fp);
    fclose(fp);

    srand(seed);
    int k = 20;
    int max_value = 20;

    /* 
     * The k'th root of a single uniform has the same distribution as
     * the max of k uniforms. Then use inversion to convert to desired
     * output range.
     */
    int num = 1 + max_value * exp( log( ((double)rand()) / RAND_MAX ) / k );
    printf("%d is the max of %d samples in the range 1..%d\n", num, k, max_value);
    return 0;
}

与1..20范围内最多20个随机数具有相同的分布,无需循环!根据{{​​1}}的大小以及k函数的价格,这真的可以带来回报。