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

james has posted 5 posts at DZone. View Full User Profile

猜数字游�

02.09.2006
| 3182 views |
  • submit to reddit
        这个程�还有一些问题,但是基本上已��以使用了

#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;
}