Game Series ~ Guess the Number (4)

#include <cstdlib>
#include <cmath>
#include <ctime>
#include <iostream>
using namespace std;
#define NUM 4
// Randomly generate 4 numbers as answers for users to guess
void answer(int *a, int s)
{
int i, j;
srand(time(NULL));
for (i = 0; i < s; ++i)
{
a[i] = rand()%10;
// make sure the currently generated random number Different from the previous
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); // Determine if the number entered by the user is valid, if invalid, re-receive the input
// Decompose the number
while (n)
{
g[i--] = n%10; n /= 10;
}
// Verify the input
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;
}
}
// Check if the input number is correct
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;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325039880&siteId=291194637