我应该如何实现随机数或随机数算法的数组以随机顺序显示报价? [英] How exactly should I implement a shuffle or random-number algorithm for an array to display quotes in random order?

查看:186
本文介绍了我应该如何实现随机数或随机数算法的数组以随机顺序显示报价?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经知道这种事情有答案,但我真的不知道如何在我的代码中实现它们。此外,我想避免使用任何更多的功能,除非必要。
这是我的代码:

I already know there's answers for this kind of thing, but I don't really know how to implement them in my code. Also, I would like to refrain from using any more functions unless neccessary. Here's my code:

int main()
{
 unsigned seed;
 seed = 1;
 srand(seed);
 std::string starFox[8];
 int x[8];
 starFox[0] = "Do a barrel roll!";
 starFox[1] = "Try a somersault!";
 starFox[2] = "Use bombs wisely!";
 starFox[3] = "Something is wrong with the G-diffuser";
 starFox[4] = "Can't let you do that, Star Fox";
 starFox[5] = "Hey Einstein, I'm on your side";
 starFox[6] = "Whoa! help me!";
 starFox[7] = "Daddy screamed REAL good before he died!";

 for(int i=0; i<8; i++)
 {
  int y = 0 + rand() % 8;
  x[i] = y;

  if (x[i-1]!=y || x[i-2]!=y || x[i-3]!=y || x[i-4]!=y || x[i-5]!=y || x[i-6]!=y || x[i-7]!=y)
  {//now I need to make a statement that makes sure each number appears once.
   std::cout << starFox[y] << "\n";}
 }
 std::cout << '\n';

 return 0;
}

因此,我应该修改这些代码,使其生成随机数程序执行的时间?

So, what should I alter about this code to make it generate random numbers each time the program executes?

推荐答案

每次运行时,你都在播种相同的值,所以你总是得到伪随机序列。尝试此操作:

You're seeding the same value every time you run, so you'll always get the same pseudo-random sequence. Try this:

srand(time(0));

这篇关于我应该如何实现随机数或随机数算法的数组以随机顺序显示报价?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆