2015-03-19 71 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()