【问题标题】:Selection Sort Code with srand input带有 srand 输入的选择排序代码
【发布时间】:2015-03-19 07:12:32
【问题描述】:

我的导师让我们负责编译一个代码,我们用 C 语言编写一个选择排序代码,就像我在网上找到的这个,

#include <stdio.h>

int main()
{
   int array[100], n, c, d, position, swap;

   printf("Enter number of elements\n");
   scanf("%d", &n);

   printf("Enter %d integers\n", n);

   for ( c = 0 ; c < n ; c++ )
      scanf("%d", &array[c]);

   for ( c = 0 ; c < ( n - 1 ) ; c++ )
   {
      position = c;

      for ( d = c + 1 ; d < n ; d++ )
      {
         if ( array[position] > array[d] )
            position = d;
      }
      if ( position != c )
      {
         swap = array[c];
         array[c] = array[position];
         array[position] = swap;
      }
   }

   printf("Sorted list in ascending order:\n");

   for ( c = 0 ; c < n ; c++ )
      printf("%d\n", array[c]);

   return 0;
}

我们必须使用srand() 命令生成一组随机数字,而不是输入数字数组。

我已经玩了大约 4 个小时了,但我似乎无法理解它。
请在使用srand()rand() 方面确实需要帮助

【问题讨论】:

  • 您使用srand() 为随机数生成器播种(一次)。您使用rand() 实际生成数字。我在这段代码中都没有看到,所以我不确定过去四个小时发生了什么。
  • 你的导师,可怜的家伙!

标签: c sorting selection-sort


【解决方案1】:

首先,srand() 用于为随机数生成器播种。你可以用rand()生成随机数

阅读本文了解更多信息

in C, how does srand relate to rand function?

您需要使用srand() 为随机数生成器播种(以便我们在每次运行程序时获得不同的值)并使用rand() 生成数字。

而不是 scanf() ,只需使用 array[c] = rand() % 100 ; (这会产生 0 到 99 之间的随机数,您可以将 100 更改为任何其他整数)。这段代码可以作为参考

#include <stdio.h>
#include<time.h>                  //  for time()
#include<stdlib.h>                // for rand()
int main()
{
    srand(time(NULL));                       // seeding the random number generator
   int array[100], n, c, d, position, swap;

   printf("Enter number of elements\n");
   scanf("%d", &n);

   printf("Enter %d integers\n", n);

   for ( c = 0 ; c < n ; c++ )
      array[c]=rand()%100;                 // storing a random number between 0 and 100 ( Note that this might produce the same number more than once )

   for ( c = 0 ; c < ( n - 1 ) ; c++ )
   {
      position = c;

      for ( d = c + 1 ; d < n ; d++ )
      {
         if ( array[position] > array[d] )
            position = d;
      }
      if ( position != c )
      {
         swap = array[c];
         array[c] = array[position];
         array[position] = swap;
      }
   }

   printf("Sorted list in ascending order:\n");

   for ( c = 0 ; c < n ; c++ )
      printf("%d\n", array[c]);

   return 0;
}

我还添加了@WhozCraig 评论中的链接,因为它会很有用

srand()

rand()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 1970-01-01
    • 2015-07-23
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    相关资源
    最近更新 更多