我想把一个随机的水果或蔬菜放进我的主阵列。程序刚停止,并没有告诉我错误是什么。我确信我的问题在于randompick功能,但对我来说似乎都没问题。
#include <iostream>
#include <string>
#include<cstdlib>
#include<ctime>
using namespace std;
class BoxOfProduce
{
private:
string veggies[4];
string fruits[4];
string ary[4];
public:
void setItemAry();
void randomPick();
//constructor
BoxOfProduce();
void display();
};
BoxOfProduce::BoxOfProduce()
{
srand(time(0));
}
void BoxOfProduce::setItemAry()
{
int x;
string item;
string item2;
for(x=0;x<4;x++)
{
cout<<"Please enter type of vegi: ";
getline(cin,item);
veggies[x]= item;
}
for(x=0;x<4;x++)
{
cout<<"Please enter type of fruit: ";
getline(cin,item2);
fruits[x]= item2;
}
}
void BoxOfProduce::randomPick()
{
int x;
int y;
int i= 0;
while (i < 4)
x = (1+(rand)()%2);
//if x one then veggies array
if (x ==1)
{
y = (rand)()%4;
ary[i]= veggies[y];
}
//if x = 2 then fruit array
else
{
y = (rand)()%4;
ary[i]=fruits[y];
}
i++;
}
void BoxOfProduce::display()
{
int x;
for(x=0;x<4;x++)
{
cout<<veggies[x]<<endl;
cout<<fruits[x]<<endl;
cout<<ary[x]<<endl;
}
}
int main()
{
BoxOfProduce fruits;
fruits.setItemAry();
fruits.randomPick();
fruits.display();
getchar();getchar();
return 0;
}
答案 0 :(得分:2)
在randomPick()
while (i < 4)
x = (1+(rand)()%2);
i
索引在哪里?这是一个无限循环。
所以请在while{.....}
中添加大括号。
像
while (i < 4)
{
x = (1+(rand)()%2);
//if x one then veggies array
if (x ==1)
{
y = (rand)()%4;
ary[i]= veggies[y];
}
//if x = 2 then fruit array
else
{
y = (rand)()%4;
ary[i]=fruits[y];
}
i++;
}
另请注意,当您在循环内部需要更大的代码块时,请先写入while(){........}
,然后再编写代码。
答案 1 :(得分:2)
由于您忘记在{
之后添加while (i < 4)
,并在下面的函数中在指令}
之后添加结束括号i++;
,因此您的while将仅执行下一条指令的无穷大{ {1}}。该指令不会更新用于打破while条件的x = (1+(rand)()%2);
。
在这种情况下,i
将始终保持为0,条件i
将始终为真且您的程序不会停止
(i < 4)