2015-03-19 47 views
-2

我的教练把我们负责编制,我们做一个选择排序的代码在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()

+1

您使用有用['函数srand ()'](http://en.cppreference.com/w/c/numeric/random/srand)播种随机数发生器(**一次**)。你可以使用['rand()'](http://en.cppreference.com/w/c/numeric/random/rand)来实际生成数字。我在代码中看不到任何内容,因此我不确定过去四个小时内发生了什么。 – WhozCraig 2015-03-19 07:22:56

+0

你的老师,可怜的家伙! – 2015-03-19 08:28:44

回答

0

首先,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()