养鱼游戏,喂鱼的循环代码前几次总是出错,每只第一次被喂的时候总是不增加,之后才能正常运行。这是为什么啊。。
```c++
#include<iostream>
#include<string>
#include<ctime>
#include<cstdlib>
using namespace std;
class Fish
{
private:
string _name,_color;
int _weight,_when;
public:
Fish(){};
Fish(string name,string color,int weight,int when):_name(name),_color(color),_weight(weight),_when(when){}
int Eat(int &weight);
int Lose(int d);
int ChangeWhen(int &when,int d);
int IsDeath()const;
void Show();
void ShowName();
};
int Fish::Eat(int &weight)
{
weight+=10;
_weight=weight;
}
int Fish::Lose(int d)
{
if((d-_when)%5==0)
{
_weight-=10;
}
}
int Fish::ChangeWhen(int &when,int d)
{
when=d;
_when=when;
}
int Fish::IsDeath()const
{
if(_weight==0){return 1;}
else if(_weight==300){return 1;}
else{return 0;}
}
void Fish::Show()
{
cout<<_name<<" "<<_color<<" "<<_weight<<"g "<<"第"<<_when<<"天"<<endl;
}
void Fish::ShowName()
{
cout<<_name;
}
int AllDeath(Fish *fish,int n,int i)
{
for(i=0;i<n;i++)
{
fish[i].IsDeath();
if(fish[i].IsDeath()==0)
{
return 0;
break;
}
}
if(i==n){return 1;}
}
int main()
{
int N,i,j,random,day=0,total;
string who;
char answer;
cout<<"您要养几条鱼(N>=5):";
cin>>N;
total=N;
string *name=new string[N];
string *color=new string[N];
int *weight=new int[N];
int *when=new int[N];
Fish *f=new Fish[N];
for(i=0;i<N;i++)
{
weight[i]=100;
when[i]=0;
cout<<"请输入第"<<i+1<<"条鱼的名字、颜色:";
cin>>name[i];
cin>>color[i];
f[i]=Fish(name[i],color[i],weight[i],when[i]);
}
cout<<"开始养鱼了!"<<endl;
do
{
srand((unsigned)time(0));
random=rand()%total;
day++;
cout<<"第"<<day<<"天:";
for(i=0;i<total;i++)
{
if(i==random)
{
f[i].Eat(weight[i]);
f[i].ChangeWhen(when[i],day);
f[i].ShowName();cout<<"吃到了食物"<<endl;
}
}
for(i=0;i<total;i++)
{
f[i].Lose(day);
}
for(i=0;i<total;i++)
{
if(f[i].IsDeath()==1)
{
for(j=i;j<total-1;j++)
{
f[j]=f[j+1];
total--;
}
}
}
for(i=0;i<total;i++)
{
f[i].Show();
}
if(day%10==0&&day/10!=0)
{
cout<<"还有"<<total<<"条活着的鱼,它们的情况是:"<<endl;
cout<<"名字"<<" "<<"颜色"<<" "<<"体重"<<" "<<"上次吃食时间"<<endl;
for(i=0;i<total;i++)
{
f[i].Show();
}
}
if(AllDeath(f,total,i)==1)
{
cout<<"抱歉,所有的鱼都死了,养鱼失败了,程序结束。";
break;
}
else
{
cout<<"您要结束养鱼吗?(Y/N):";
cin>>answer;
if(answer!='Y')
{
AllDeath(f,total,i);
}
else
{
cout<<"程序结束。";
break;
}
}
}
while(AllDeath(f,total,i)==0);
return 0;
}
```