解答C++作业03

王朝c/c++·作者佚名  2006-01-09
宽屏版  字体: |||超大  

#include<cstdlib>

#include<ctime>

#include<string>

#include<iostream>

#include<conio.h>

using namespace std;

const int SECRET_SIZE=10; // size of secret number array

const int GUESS_SIZE=4; // size of guess number array

void initialize_secret( int secret[] )

{

int i;

srand((int)time(0));

for (i=0;i<SECRET_SIZE;i++)

{

secret[i]=(rand())%10;

}

}//use time as seeds

void read_guess( int guess[] )

{

string str;

char ch;int i=0;

cout<<"guess:"<<endl;

do{

ch=getch();

if(ch>='0'&&ch<='9')

{

putchar(ch);

putchar(' ');

str=str+ch;i++;

}//ignore other input

// if(ch==13) cout<<endl;

}while(i<4);

guess[0]=(int)str[0]-48;

guess[1]=(int)str[1]-48;

guess[2]=(int)str[2]-48;

guess[3]=(int)str[3]-48;

cout<<endl;

}

bool no_match(int secret[], int guess[] )

{

int i,j,cowCount=0,bullCount=0;

for(i=0;i<4;i++)

{

for(j=0;j<4;j++)

{

if(secret[i]==guess[j])

{

if(i==j) bullCount++;else cowCount++;

break;//since the 4 number are different;

}

}//end for

}//end for

cout<<"bull:"<<bullCount<<" cow:"<<cowCount<<endl;

if (bullCount==4) return false;

else return true;

}

void display(int secret[])

{

int i;

for(i=0;i<4;i++)

cout<<secret[i]<<" ";

cout<<endl;

}

bool same(int secret[])

{

int i,j;

for(i=0;i<4;i++)

for(j=i+1;j<4;j++)

if(secret[i]==secret[j]) return true;

return false;

}

int main()

{

int secret[SECRET_SIZE];

int guess[GUESS_SIZE],guessTime=0;

do{

initialize_secret(secret);

}while(same(secret));//make sure the numbers are different

cout<<"Melcome to MOO!!!!!!"<<endl;

cout<<"***************************************************************\n"

"Moo is a guessing game imported from England.\n"

"The computer picks a number consisting of four distinct decimal digits.\n"

"YOU guess four distinct digits being scored on each guess.\n"

"A \"cow\" is a correct digit in an incorrect position. \n"

"A \"bull\" is a correct digit in a correct position.\n"

"The game continues until YOU guesses all the number.(a score of four bulls)\n"

"Input four 0 to show secret. :)\n"

"enioy it!!!!!! :)\n"

"***************************************************************\n"<<endl;

//description

do{

read_guess(guess);

guessTime++;

if (guess[0]==0&&guess[1]==0&&guess[2]==0&&guess[3]==0)

display(secret);

}while(no_match(secret,guess));

cout<<"YOU finally succeed!"<<endl;

cout<<"YOU have tried "<<guessTime<<" times!"<<endl;

cout<<"Welcome to replay this game!!!!!!"<<endl;

return 0;

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有