游戏系列~猜数字(4)

#include <cstdlib>
#include <cmath>
#include <ctime>
#include <iostream>
using namespace std;
#define NUM 4
// 随机产生4个数字,作为答案供使用者猜测
void answer(int *a, int s)
{
int i, j;
srand(time(NULL));
for (i = 0; i < s; ++i)
{
a[i] = rand()%10;
// 确保当前产生的随机数与前面产生的不同
for (j = 0; j < i; ++j)
if (a[i] == a[j])
{
a[i] = rand()%10;
j = -1;
continue;
}
}
}
int main(void)
{
int a[NUM], g[NUM]={0, 0, 0, 0}, i, j, n, x, y;
char choice;
answer(a, NUM);
cout << "***Welcome To This Little Game***" << endl << endl;
cout << "Please input a 4-digit number: " << endl;
while (1)
{
x = y = 0;
i = NUM-1;
do
{
cin >> n;
} while (n < 0 || n > 9999); // 判断用户输入的数字是否有效,无效重新接收输入
// 分解数字
while (n)
{
g[i--] = n%10; n /= 10;
}
// 验证输入
for (i = 0; i < NUM; ++i)
{
if (a[i] == g[i])
x += 1;
else
{
for (j = 0; j < NUM; ++j)
if (a[i] == g[j])
y += 1;
}
}
// 判断输入数字是否猜对
if (4 == x)
{
cout << "Congratulations!" << endl;
break;
}
else
{
cout << "Sorry, you haven't guess the right number!" << endl;
cout << x << 'A' << y << 'B' << endl;
cout << "Do you want to continue(y or n)?" << endl;
cin >> choice;
if (choice != 'y' && choice != 'Y')
{
cout << "Right number is:" << a[0] << a[1] << a[2] << a[3] << endl;
break;
}
}
}
cout << "exiting.." << endl;
}

猜你喜欢

转载自www.cnblogs.com/yszhyhm/p/8969584.html
今日推荐