0
#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 中显示 1-20 之间的“随机”数字。像 1 19 6 8 18 6 8 等。有些数字或多或少地重复。

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

4

3 回答 3

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);
于 2013-11-02T14:22:53.040 回答
0

尝试这个

int biggest = 0, num;


for(i=0; i < 20; i++)
{   
    num = 1 + rand()%20; 
    if (biggest < num)
        biggest = num;  
}       
printf("%d \n", biggest);
于 2013-11-02T14:27:10.320 回答
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 个随机数具有相同的分布,无需循环!取决于k你的功能有多大和有多昂贵rand(),这真的可以得到回报。

于 2013-11-02T18:45:39.507 回答