【问题标题】:rand() sometimes outputs blank lines, and other times it works just finerand() 有时会输出空行,有时它工作得很好
【发布时间】:2015-10-27 17:50:27
【问题描述】:

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

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

有时输出如下所示: (空行) 番茄 (空行)

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

#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");
}

【问题讨论】:

    标签: c++ random


    【解决方案1】:

    这一行:

    displayWord(boxInt); //display it
    

    应该是:

    displayWord(i); //display it
    

    【讨论】:

    • 天啊...这不是我第一次犯这样的错误。非常感谢你清理它。解决方案如此简单,我感到很尴尬。再次感谢!
    【解决方案2】:

    这里有几个变化:

    while (userInput = 'y');
    

    应该是:

    while (userInput == 'y');
    

    displayWord(boxInt);
    

    应该是:

    displayWord(i);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-08
      • 2013-07-04
      相关资源
      最近更新 更多