DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world
çŒœæ•°å—æ¸¸æˆ?
这个程�还有一些问题,但是基本上已��以使用了
#include "stdafx.h"
#include "stdlib.h"
#include "time.h"
#include <iostream>
const int RANGE_MAX = 9999;
const int RANGE_MIN = 1000;
using namespace std;
/*
猜数å—的游æˆ?.è¦?求如下:
规则:
电脑�机生�4个数,范围1-9,比如1234。
ä½ çŒœ4个数,当数å—相å?Œä½?置相å?Œåˆ™ä¸ºä¸€ä¸ªA,当数å—相å?Œä½?ç½®ä¸?å?Œåˆ™ä¸ºä¸€ä¸ªB
æ¯”å¦‚ä½ çŒœ2345,则是3B
ä½ çŒœ1398,则是1A1B
�制次数,比如�让自己猜8次
*/
class GuessNum
{
public:
void layer(int times); // 猜测的次数
GuessNum();
int Compare(int the_number); // 返回匹é…?的结果,比如1A,1A1Bç‰ç‰.
int Compare(char number[]);
~GuessNum();
private:
int _times;
char _the_number[4];
char compare_num[4];
};
void GuessNum::layer(int times)
{
srand((unsigned)time(NULL));
int temp_value = 0;
for(int i = 0; i < 10; i++)
{
temp_value = (int)(((double) rand() / (double) RAND_MAX) * RANGE_MAX + RANGE_MIN);
}
if(temp_value > 9999)
{
temp_value -= RANGE_MIN;
}
else if(temp_value<1000)
{
temp_value+=RANGE_MIN;
}
sprintf(_the_number, "%d", temp_value);
cout << "The number is " << _the_number << endl;
_times = times;
}
GuessNum::GuessNum()
{
layer(8);
}
GuessNum::~GuessNum(){}
int GuessNum::Compare(int number)
{
if(number < 1000 || number > 9999)
{
cout << "您输入的数å—" << number << "是ä¸?对的,请é‡?新输入.\næ•°å—è¦?求在1000å’Œ9999之间" << endl;
return -1;
}
_the_number;
//char compare_num[4];
sprintf(compare_num, "%d", number);
Compare(compare_num);
return 0;
}
int GuessNum::Compare(char number[])
{
int exactly_match_number = 0;
int match_number = 0;
int i,j;
//cout << _the_number <<"||||||||||"<< endl;
//cout << "The number is " << _the_number << endl;
for(i = 0; i < 4; i++)
{
for(j = 0; j < 4; j++)
{
if(number[i] == _the_number[j]&&_the_number[j]-number[j]&&_the_number[i]-number[i]) // 有数å—的匹é…?
{
match_number++;
}
}
}
for(i = 0; i < 4; i++)
{
if(number[i] == _the_number[i]) // 有完全的匹�
{
exactly_match_number++;
}
}
cout << "æ‚¨è¾“å…¥çš„æ•°å—æ˜¯'" << number << "',匹é…?的结果是 ";
if(exactly_match_number > 0)
{
cout << exactly_match_number << "A";
}
cout << match_number<< "B";
cout << endl;
return 0;
}
int main()
{
GuessNum guess;
cout << "请输入您想è¦?猜测的数å—" << endl;
int number;
for(int i = 0; i < 8; i++)
{
cin >> number;
guess.Compare(number);
}
system("PAUSE");
return 0;
}




