一个判断猫是否会打架的问题!我的随机数产生好像有问题!
ztwz 2004-12-12 06:27:50 //问题:为什么我的随机数产生的都是同一个数?我以用时间做过种子了!
#ifndef cat_h
#define cat_h
class cat
{
public:
cat();
const char *getFurColor() const;
const char *getHairLength() const;
const char *getEyeColor() const;
private:
void setFurColor();
void setHairLength();
void setEyeColor();
char *furColor;
char *hairLength;
char *eyeColor;
};
#endif
-------------------------------------------------
#include <iostream>
#include <time.h>
#include "cat.h"
using namespace std;
cat::cat()
{
srand(time(0));//我做种了呀 ̄ ̄ ̄ ̄ ̄
setFurColor();
setEyeColor();
setHairLength();
}
const char *cat::getFurColor() const //返回猫的毛皮色
{
return furColor;
}
const char *cat::getEyeColor() const //返回猫的眼睛颜色
{
return eyeColor;
}
const char *cat::getHairLength() const //返回猫的毛长短
{
return hairLength;
}
void cat::setFurColor() //随机产生毛皮颜色
{
int x=rand()%3;
if(x==0)
furColor="black";
else if(x==1)
furColor="gray";
else
furColor="brown";
}
void cat::setEyeColor() //随机产生猫眼睛颜色
{
int x=rand()%3;
if(x==0)
eyeColor="bule";
else if(x==1)
eyeColor="brown";
else
eyeColor="green";
}
void cat::setHairLength() //随机产生毛的长短
{
int x=rand()%2;
if(x==0)
hairLength="short";
else
hairLength="long";
}
-------------------------------------------
#include <iostream>
#include <stdlib.h>
#include "cat.h"
using namespace std;
void check(cat *pen[],int);
int main(int argc, char *argv[])
{
const int pen_size=7;
cat *pen[pen_size];
for(int c=0;c<pen_size;c++)
{
pen[c]=new cat;
}
for(int c=0;c<pen_size;c++)
{
check(pen,pen_size);
cout<<"Press a key to add the next cat."<<endl;
cin.get();
}
for(int i=0;i<pen_size;i++)
delete pen[i];
system("PAUSE");
return 0;
}
void check(cat *catpen[],int numberOfCats)
{
int brownCats=0, grayCats=0, blueEyes=0,
greenEyes=0, brownEyes=0;
for(int x=0;x<numberOfCats;x++)
{
if(strcmp(catpen[x]->getFurColor(),"gray")==0)
++grayCats;
if(strcmp(catpen[x]->getFurColor(),"brown")==0)
++brownCats;
if(strcmp(catpen[x]->getEyeColor(),"blue")==0)
++blueEyes;
if(strcmp(catpen[x]->getEyeColor(),"green")==0)
++greenEyes;
if(strcmp(catpen[x]->getEyeColor(),"brown")==0)
++brownEyes;
}
if(grayCats>brownCats)
cout<<"The gray cats are fighting with the brown cat"
<<(brownCats>1?"s.":".")<<endl;
cout<<"brownCats:"<<brownCats<<"\n"<<"grayCats:"<<grayCats<<endl;
//if()//这儿还没写完,要求是当围栏里至少一只一只黑色绿眼的猫,和至少一只黑色蓝眼的猫时,哪果在放入一只且仅为一只黑色的棕眼猫,黑色的猫之间就会打架,如果围栏里的黑色棕眼猫多于一只,黑猫之间就不会打架
cout<<"The black cat(s) with blue eyes and the black"
<<"cat(s) with green eyes are\nfighting with the"
<<" black cat that has brown eyes."<<endl;
}