2010-08-15 217 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

一旦你完成了这么多,请粘贴你的代码。希望你能理解这个问题的逻辑。