rand()有时输出空白行,有时候它工作得很好

时间:2015-10-27 17:50:28

标签: c++ random

当这个程序运行时,它应该随机显示3个不同的水果/蔬菜(重复是可以的)但有时一个或多个输出是空白的,我不知道如何纠正这个。它还会计算并显示您选择运行程序的次数。

有时输出如下: 西兰花 猕猴桃 猕猴桃

有时输出看起来像这样: (空行) 番茄 (空行)

我该如何解决这个问题?我确定问题出在for {循环boxInt

的某个地方
#include <iostream>
#include <string>
#include <cstdlib>
#include <ctime>
using namespace std;

const int BOX_SIZE = 3;

class BoxOfProduce
{
public:
    BoxOfProduce();
    void displayWord(int boxInt);
    void input();
    void output();
    string Box[BOX_SIZE];

private:
    string full_list[5];
    static int count;
};


int BoxOfProduce::count = 0;


BoxOfProduce::BoxOfProduce()
{
    full_list[0] = { "Broccoli" };
    full_list[1] = { "Tomato" };
    full_list[2] = { "Kiwi" };
    full_list[3] = { "Kale" };
    full_list[4] = { "Tomatillo" };
}


void BoxOfProduce::input(){}


void BoxOfProduce::output()
{
    srand(time(0));

    int i;
    cout << "your bundle: " << endl;
    for (i = 0; i < 3; i++) // loop to execute code 3 times
    {
        int boxInt = rand() % 5; //make random number
        Box[i] = full_list[boxInt]; //add it to the Box
        displayWord(boxInt); //display it
    }
}
void BoxOfProduce::displayWord(int boxInt)
{
    cout << Box[boxInt] << endl;
}

int main()
{
    char userInput;
    static int counter = 0; // static variable for keeping track of how many boxes the user has opened

    do
    {
        cout << "Open new box of random produce? (y/n): ";
        cin >> userInput;

        if (userInput == 'y')
        {
            counter++;
            BoxOfProduce box1;
            box1.input();
            box1.output();

            cout << "\nCurrent number of produces boxes: " << counter << endl << endl;
        }
        else
        {
            return 0;
        }
    } while (userInput = 'y');

    system("pause");
}

2 个答案:

答案 0 :(得分:3)

这一行:

displayWord(boxInt); //display it

应该是:

displayWord(i); //display it

答案 1 :(得分:3)

这里有一些变化:

while (userInput = 'y');

应该是:

while (userInput == 'y');

displayWord(boxInt);

应该是:

displayWord(i);