C语言中的随机数不是随机数

C语言中的随机数不是随机数,c,random,C,Random,这是我的程序代码。它应该从用户那里得到两个数字,然后使用rand函数生成随机数。 但是当我编译它时,这些数字不是随机的 我也用java写了这篇文章,这篇文章非常好用 C版本: #include <stdio.h> #include <stdlib.h> #include <time.h> int cmpfunc(); int main() { puts("How many numbers do you want to generate?");

这是我的程序代码。它应该从用户那里得到两个数字,然后使用rand函数生成随机数。 但是当我编译它时,这些数字不是随机的

我也用java写了这篇文章,这篇文章非常好用

C版本:

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

int cmpfunc();

int main()
{
   puts("How many numbers do you want to generate?");
   int n;
   scanf("%d", &n);
   int numbers[n];

   puts("What should be the largest number possible?");
   int m, i;
   scanf("%d", &m);
   int result[m];

   for(i=0;i<m;i++)
       numbers[i] = i + 1;

       srand(time(NULL));
   for(i=0;i<n;i++)
   {
       int r = rand() % m;

       result[i] = numbers[r];
       numbers[r] = numbers[m - 1];
       m--;

   }

   qsort(result, n, sizeof(int), cmpfunc); //sorting the result array

   for(i=0;i<n;i++)
   {
       printf("%d\n", result[i]);
   }

    getch();
    return 0;
}

int cmpfunc (const void * a, const void * b)
{
   return ( *(int*)a - *(int*)b );
}
编辑:srand在循环中,人们说它不应该被多次调用。所以我把它拿了出来,但那没用

Java版本:

import java.util.*;

public class RandomNumberGenerator {

    public static void main(String[] args) {

        Scanner in = new Scanner(System.in);

        System.out.println("How many numbers do you want to generate?");
        int n = in.nextInt();

        System.out.println("What should be the largest number possible?");
        int m = in.nextInt();

        int numbers[] = new int[m];
        for(int i=0;i<numbers.length;i++)
            numbers[i] = i + 1;

        int result[] = new int[n];
        for(int i=0;i<result.length;i++)
        {
            // make a random index between 0 and n - 1
            int r = (int) (Math.random() * m );

            result[i] = numbers[r];
            // move the last element into the random location
            numbers[r] = numbers[m - 1];
            m--;
        }

        System.out.println("Do you want the result to be sorted? (1 for Yes, others for No)");
        int ans = in.nextInt();

        if(ans==1)
            Arrays.sort(result);

          System.out.println("Result:");
          for (int r : result)
             System.out.println(r);

          pressAnyKeyToContinue();

    }

    private static void pressAnyKeyToContinue()
     { 
            System.out.println("Press Enter to continue.");
            try
            {
                System.in.read();
            }  
            catch(Exception e)
            {}
     }

}
编辑2:

c输出:不是随机的,已排序

java输出:是随机的、排序的

编辑3:

如我在评论中所述,价值观为: n=55 m=9808

另外,我使用代码块,所以头文件不是一个真正的问题。它们由代码块自动加载

编辑4:

人们的建议给我留下了深刻的印象。qsort不会改变生成随机数的过程。它只是对数组进行排序。所以即使我移除它,它也不会改变任何东西

在一个随机数数组中,我们期望任意两个相邻元素之间的差也是随机的。此属性在排序下保留。我对C和Java中的随机数进行排序,以检查这个属性。正如您所看到的,在C代码中,相邻元素之间的差异都是相同的。这让我相信C代码并不是在生成随机数,而是Java代码在生成随机数

编辑5:

我确信java和c之间的算法应该没有什么不同

编辑6:

很抱歉,我不是专业人士。我只是想把我的Java程序做成一个C版本。一个固定的代码将非常感谢

****编辑最终版本:** 终于开始工作了。分别存储n和m的数组编号和结果应该存储m和n。这就是全部。除此之外,我根据人们的建议更改了他们的名字。有些人告诉我用数组dim来切换变量m和n。事实并非如此。 以下是所有感兴趣的人的固定代码:**

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

int cmpfunc();

int main()
{
   puts("How many numbers do you want to generate?");
   int  num_numbers;
   scanf("%d", &num_numbers);

   puts("What should be the largest number possible?");
   int num_maximum, i;
   scanf("%d", & num_maximum);


   int numbers[num_maximum];
   int result[num_numbers];

   for(i=0;i<num_maximum;i++) // making
       numbers[i] = i + 1;

       srand(time(NULL)); // seeding rand

   for(i=0;i<num_numbers;i++)
   {
       int r = rand() %  num_maximum; // generates random number between 0 and m-1

       result[i] = numbers[r]; //

       numbers[r] = numbers[ num_maximum - 1];
        num_maximum--;

   }

   puts("Do you want the result to be sorted?");
   int ans;
   scanf("%d", &ans);

   if (ans==1)
   qsort(result,  num_numbers, sizeof(int), cmpfunc); //sorting the result array

   for(i=0;i< num_numbers;i++)
   {
       printf("%d\n", result[i]);
   }

    getch();
    return 0;
}

int cmpfunc (const void * a, const void * b)
{
   return ( *(int*)a - *(int*)b );
}
srandtimeNULL;用于为随机数生成器设定种子。它只需要调用一次。你需要把它移出for循环

如果你每次都播种,你最终会得到兰德公司生产的相同数量的种子

而且,时间是时间的原型

接下来,正如@blastfurne所提到的,您应该将m而不是n作为第二个参数传递给qsort

那么

may将为数字数组生成越界访问,从而导致UB。

问题是:

n= 55 m= 9808
然而,该守则包括:

int numbers[n];

for(i=0;i<m;i++)
   numbers[i] = i + 1;
然后你可以使用它:

for (int i = 0; i < dimof(numbers); ++i)
    numbers[i] = i + 1;
这样就不可能混淆哪个变量和哪个数组

您必须对第二个循环和qsort维度执行相同的操作。

在Java代码中:

the following code may be what your looking for:

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

int cmpfunc (const void * a, const void * b);

int main()
{
    puts("How many numbers do you want to generate?");
    int n;
    scanf("%d", &n);

    puts("What should be the largest number possible?");
    int m;
    scanf("%d", &m);
    int result[n];

    int i;

    srand(time(NULL));

    for(i=0;i<n;i++)
    {
        result[i] = rand() % m;
    }

    qsort(result, n, sizeof(int), cmpfunc); //sorting the result array

    for(i=0;i<n;i++)
    {
        printf("%d\n", result[i]);
    }

    getchar();
    return 0;
} // end function: main


int cmpfunc (const void * a, const void * b)
{
    return ( *(int*)a - *(int*)b );
} // end function: cmpfunc
int numbers[] = new int[m];
int result[] = new int[n];
在您的C代码中:

int numbers[n];
int result[m];

数组的大小是相反的。当我将C代码的定义与Java代码的定义相匹配时,代码似乎可以工作。

因为这比指出每个错误更容易,下面是Java代码到C的音译,其中包含一些更有意义的变量名Horstmann应该更清楚,但没有排序代码,这会让人分心:

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

int main( void )
{
  int sampleSize, valueRange;
  printf( "How many samples do you want to take: " );
  fflush( stdout );
  scanf( "%d", &sampleSize );

  printf( "What is the range of values, starting from 1: " );
  fflush( stdout );
  scanf( "%d", &valueRange );

  /**
   * The numbers array contains your source values, ranging
   * from 1 to valueRange.  The result array contains a random,
   * non-repeating sample of the numbers array.
   */
  int numbers[valueRange];
  int result[sampleSize];

  for ( int i = 0; i < valueRange; i++ )
    numbers[i] = i + 1;

  srand( time( NULL ));

  for ( int i = 0; i < sampleSize; i++ )
  {
    int sampleIndex = rand() % valueRange;
    result[i] = numbers[sampleIndex];
    numbers[sampleIndex] = numbers[ valueRange - 1 ];
    valueRange--;
  }

  for ( int i = 0; i < sampleSize; i++ )
    printf( "result[%4d] = %d\n", i, result[i] );

  return 0;
}
像这样使用可变长度数组时要小心;如果为范围或样本大小输入足够大的值,则会超出堆栈空间并出现运行时错误。使用malloc或calloc分配空间会更安全,但对于较小的范围和样本量,这肯定更容易,也更少麻烦


此外,还应该添加一些代码,以确保样本大小始终小于值范围。还是坏事™ 将发生。

可能需要。发布的代码丢失,包括在windows上的conio.h中找到getch。。。强烈建议使用getchar而不是getch,原因之一是conio.h是特定于windows的,所以不是portable@VSG24我有一个建议。您能否编辑您的问题,以包含再现问题的最小示例?当前的错误、糟糕的代码似乎是一种干扰。顺便说一句,兰德确实有效。如果qsort不重要,你不应该把它包括在你的问题中。最好的问题是那些提供演示问题所需的最少代码量的问题。花更多的时间提前提出一个好问题将节省您的时间和精力。另外,考虑一下你的问题的标题。C是随机数,使用它们是错误的。另一个想法是使用有意义的变量名,如num_numbers和num_result,这样就不太可能使维度与arrays@VSG24m和n的值是多少?n=55,m=9808。不管是什么号码。结果不是随机的。。。srand与randsorry不在同一个循环中。对不起,是向上投票,而不是向下投票。希望给你+9而不是+0请停止谈论srand。它在循环中,他说要把它弄出来,我做了,但没有用。因此,srand不是问题。此实现可以
吃随机数。问题中的代码试图传递n个唯一的随机变量numbers@MattMcNabb确切地说,集合中的每一个元素都必须是唯一的,因为它是单调的。我只想让它在m>n时工作。我知道这不是最好的风格代码,但它必须工作。正如在java中所做的那样。@VSG24当m>n作为我的答案,其他人指出您是否可以共享固定的代码时,它就被破坏了。无法使用您的建议修复它。@VSG24不,您必须付出一点努力。至少,您需要做的就是将代码中的m改为n,并将n改为m,因为您当前使用的代码是错误的。动动脑筋。例如,当你有fori=0;我明白了。但它现在也没什么效果了。看在上帝的份上,请给我固定的密码,这样我就可以学习了。这个程序不是一个作业或任何东西。我本来打算在5分钟内完成,但结果是这个怪物。谢谢分享这个,但我通过简单地切换数组值来修复它。
int numbers[n];
int result[m];
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

int main( void )
{
  int sampleSize, valueRange;
  printf( "How many samples do you want to take: " );
  fflush( stdout );
  scanf( "%d", &sampleSize );

  printf( "What is the range of values, starting from 1: " );
  fflush( stdout );
  scanf( "%d", &valueRange );

  /**
   * The numbers array contains your source values, ranging
   * from 1 to valueRange.  The result array contains a random,
   * non-repeating sample of the numbers array.
   */
  int numbers[valueRange];
  int result[sampleSize];

  for ( int i = 0; i < valueRange; i++ )
    numbers[i] = i + 1;

  srand( time( NULL ));

  for ( int i = 0; i < sampleSize; i++ )
  {
    int sampleIndex = rand() % valueRange;
    result[i] = numbers[sampleIndex];
    numbers[sampleIndex] = numbers[ valueRange - 1 ];
    valueRange--;
  }

  for ( int i = 0; i < sampleSize; i++ )
    printf( "result[%4d] = %d\n", i, result[i] );

  return 0;
}
[fbgo448@n9dvap997]~/prototypes/rand: ./stackrand
How many samples do you want to take: 10
What is the range of values, starting from 1: 10
result[   0] = 5
result[   1] = 6
result[   2] = 7
result[   3] = 4
result[   4] = 10
result[   5] = 3
result[   6] = 2
result[   7] = 8
result[   8] = 1
result[   9] = 9
[fbgo448@n9dvap997]~/prototypes/rand: ./stackrand
How many samples do you want to take: 10
What is the range of values, starting from 1: 10
result[   0] = 9
result[   1] = 3
result[   2] = 7
result[   3] = 1
result[   4] = 4
result[   5] = 8
result[   6] = 2
result[   7] = 5
result[   8] = 6
result[   9] = 10
[fbgo448@n9dvap997]~/prototypes/rand: ./stackrand
How many samples do you want to take: 10
What is the range of values, starting from 1: 100
result[   0] = 28
result[   1] = 90
result[   2] = 100
result[   3] = 4
result[   4] = 15
result[   5] = 76
result[   6] = 3
result[   7] = 60
result[   8] = 65
result[   9] = 21