gpt4 book ai didi

c++ - rand() 有时输出空行,其他时候它工作得很好

转载 作者:行者123 更新时间:2023-11-30 00:47:58 26 4
gpt4 key购买 nike

当这个程序运行时,它应该随机显示 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");
}

最佳答案

这一行:

displayWord(boxInt); //display it

应该是:

displayWord(i); //display it

关于c++ - rand() 有时输出空行,其他时候它工作得很好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33375117/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com