模拟文曲星上的猜数游戏,先由计算机随机生成一个各位相异的4位数字,由用户来猜,根据用户猜测的结果给出提示:xAyB 其中,A前面的数字表示有几位数字不仅数字猜对了,而且位置也正确,B前面的数字表示有几倍数字猜对了,但是位置不正确。 最多允许用户猜的次数由用户从键盘输入。如果猜对,则提示“Congratulations!”;如果在规定次数以内仍然猜不对,则给出提示“Sorry, you haven’t guess the right number!”。程序结束之前,在屏幕上显示这个正确的数字
时间: 2023-12-06 11:03:10 浏览: 30
以下是一个可以模拟文曲星猜数游戏的C++代码,供您参考:
```cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <cstring>
using namespace std;
const int MAX_TIMES = 10; // 最大猜测次数
bool is_valid(int num[], int n) {
// 判断一个数字是否各位不同
bool used[10] = {false};
for (int i = 0; i < n; i++) {
if (used[num[i]]) {
return false;
} else {
used[num[i]] = true;
}
}
return true;
}
void generate_number(int num[], int n) {
// 生成一个各位不同的n位数字
srand((unsigned)time(NULL));
do {
for (int i = 0; i < n; i++) {
num[i] = rand() % 10;
}
} while (!is_valid(num, n));
}
void guess_number(int answer[], int n, int times) {
// 猜测数字
int guess[n];
int A, B;
while (times > 0) {
cout << "请输入一个各位不同的" << n << "位数字:";
int i;
cin >> i;
for (int j = n - 1; j >= 0; j--) {
guess[j] = i % 10;
i /= 10;
}
A = B = 0;
for (int i = 0; i < n; i++) {
if (guess[i] == answer[i]) {
A++;
} else {
for (int j = 0; j < n; j++) {
if (guess[i] == answer[j]) {
B++;
break;
}
}
}
}
if (A == n) {
cout << "Congratulations!" << endl;
cout << "正确的数字是:";
for (int i = 0; i < n; i++) {
cout << answer[i];
}
cout << endl;
break;
} else {
cout << A << "A" << B << "B" << endl;
times--;
}
}
if (times == 0) {
cout << "Sorry, you haven't guess the right number!" << endl;
cout << "正确的数字是:";
for (int i = 0; i < n; i++) {
cout << answer[i];
}
cout << endl;
}
}
int main() {
int n = 4;
int answer[n];
generate_number(answer, n);
int times;
cout << "请输入可以猜测的次数:";
cin >> times;
guess_number(answer, n, min(times, MAX_TIMES));
return 0;
}
```
希望能够帮到您!