首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用for循环显示内容

使用for循环显示内容
EN

Stack Overflow用户
提问于 2015-10-28 01:55:14
回答 3查看 44关注 0票数 1

我试图编写一个程序,从包含五个不同水果或蔬菜的数组中随机选择三个条目,然后将随机选择的内容显示给用户。现在,我很难理解为什么输出是不一致的,因为有时候当我运行它时,我会得到这样的结果:

代码语言:javascript
复制
This bundle contains the following: 


Broccoli

由于前两项缺少了,有时我会得到以下内容:

代码语言:javascript
复制
This bundle contains the following: 
Tomato
Tomato
Tomato

这是我当前遇到问题的代码的一部分:

代码语言:javascript
复制
void BoxOfProduce::output() {

        cout << "This bundle contains the following: " << endl;

        // Use this so it will be truly random
        srand(time(0));

        for (int f = 0; f < 3; f++) {

            // Here were making the random number
            int boxee = rand() % 5;

            // Adding the content to the box
            Box[f] = Box[boxee];

            // Now were calling on the function to display the content
            displayWord(boxee);

        } // End of for loop

    } // End of output()


    void BoxOfProduce::displayWord(int boxee) {

        cout << Box[boxee] << endl;

    }


int main() {

    BoxOfProduce b1;
    b1.input();
    b1.output();

有人能帮我理解我为什么要得到这个输出吗?谢谢!

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2015-10-28 02:06:34

不要这样做:)就像@John3136指出的那样,你在搞乱你的Box变量。

代码语言:javascript
复制
void BoxOfProduce::output()
{

  srand(time(NULL)); //keep in mind that this is NOT entirely random!
  int boxee = rand() % 5;
  int i = 0;
  while(i<5)
  {
    boxee = rand() % 5;
    cout<<Box[boxee]<<endl;  //this line might be wrong, my point is to print element of your array with boxee index
    i++;
  }

}
票数 1
EN

Stack Overflow用户

发布于 2015-10-28 02:01:48

Box[f] = Box[boxee];正在更改您正在从中挑选的"Box“的内容。如果第一个随机数为3,则将第3项复制到项0,所以现在您有两倍的机会在下一次循环中获得该项.

票数 1
EN

Stack Overflow用户

发布于 2015-10-28 02:03:43

您正在用随机选择的项覆盖数组的元素。

代码语言:javascript
复制
Box[f] = Box[boxee];

例如:如果boxee=1f=0,它将在索引0处用1覆盖元素,而在同一时间,索引1处的元素是相同的,留下两个相同的项副本。

使用:std:随机播放代替。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/33381619

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档