2010-08-15 221 views
-2

嘿,我想問一下,如果我有一個單詞列表讓我們說'老虎,獅子,大象,斑馬,馬,駱駝,鹿,鱷魚,兔子,貓' 我可以在c編程中隨機生成5個單詞嗎? 例如:從c編程中的單詞列表生成隨機單詞

老虎,斑馬,貓,鹿,馬

鱷魚,兔子,駱駝,斑馬,大象

ECT

預先感謝您:d

編輯

#include <stdio.h> 
#include <string.h> 

#define SIZE 10 

int main() 
{ 

char arr2[SIZE][20] = { "tiger", "lion", "elephant", "zebra", "horse", "camel", "deer", "crocodile", "rabbit", "cat" }; 

int x = 0; 
srand(time(NULL)); 

while (x < SIZE - 5) 
{ 
    arr2 [x][20] = rand(); 
    printf ("%s\n", arr2[x]); 
    x++; 
} 

system ("pause"); 
return 0; 
} 
+6

到目前爲止你有什麼? – 2010-08-15 04:49:45

+2

聞起來像是我的作業 – 2010-08-15 05:02:13

+1

'arr2 [x] [20] = rand();'假設要做什麼? – qrdl 2010-08-15 07:26:24

回答

3

將單詞放入數組中。在右邊的範圍(0..array_size-1)中生成5個(或其他)僞隨機數。使用這些數字從數組中選擇單詞。

+0

我模糊了...我沒有明白。:(對不起 – falcon 2010-08-15 06:28:45

0

爲了便於說明,這是C#,但我敢肯定,你可以轉換爲C,相當容易:

static void Main(string[] args) 
    { 
     string[] words =  
       { "tiger", "lion", "elephant", "zebra", "horse", 
        "camel", "deer", "crocodile", "rabbit", "cat" }; 

     string randomWords = RandomWords.GenerateRandomWordString(5, words); 
    } 


public static class RandomWords 
{ 
    private static readonly Random _random = new Random((int)DateTime.Now.Ticks); 

    public static string GenerateRandomWordString(int numWords, string[] words) 
    { 
     int maxlen = words.Length; 

     StringBuilder sb = new StringBuilder(); 
     for (int i = 0; i < numWords; i++) 
     { 
      // Note: in .NET, Random.Next(0, max) returns 
      // a value in range zero to max - 1 
      sb.Append(words[_random.Next(0, maxlen)]); 
      sb.Append(" "); 
     } 

     return sb.ToString().Trim(); 
    } 
} 
+0

非常感謝你!!但是,嚴肅地說,我沒有任何想法如何把它轉換成C ...哦...我真的很笨= =「 – falcon 2010-08-15 06:21:41

+2

@falcon:這可以通過學習,聽力和其他東西來恢復,真的 – 2010-08-15 06:28:06

+1

@falcon:你試過了什麼? t轉換自己... – 2010-08-15 06:30:59

1

你可以做到以下幾點:

  1. 你已經有一個數組,持有元素(動物名稱)
  2. 您可以通過索引訪問每個元素,比如說k,您可以像這樣訪問數組元素arr2[k]
  3. 現在你需要得到一個隨機數,每次分配給k。這可以通過使用標準程序庫的rand函數來完成,該函數可能調用了錯誤的方法
  4. 一旦您打印出一個值需要跟蹤它,所以使用整數數組check[SIZE] = {0,}並且在打印arr2[k]之前,檢查是否check[k]==0,然後打印該值。打印後設爲arr2[k]=1

一旦你完成了這麼多,請粘貼你的代碼。希望你能理解這個問題的邏輯。