#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(NULL)); // 使用当前时间作为随机数种子
const int MAX_NUM = 100;
int secretNum = rand() % MAX_NUM + 1;
int guess;
int attempts = 0;
cout << "Welcome to the number guessing game!" << endl;
cout << "I'm thinking of a number between 1 and " << MAX_NUM << ". Can you guess it?" << endl;
while (true) {
cout << "Enter your guess: ";
cin >> guess;
attempts++;
if (guess == secretNum) {
cout << "Congratulations! You guessed the number in " << attempts << " attempts." << endl;
break;
} else if (guess < secretNum) {
cout << "Too low. Try again." << endl;
} else {
cout << "Too high. Try again." << endl;
}
}
return 0;
}
在main函数中,我们首先使用srand函数以当前时间作为随机数种子,然后使用rand函数生成一个1到MAX_NUM之间的随机整数作为答案。在while循环中,我们接受用户的输入并与答案进行比较,根据比较结果输出相应的提示信息。如果用户猜对了答案,则输出“Congratulations! You guessed the number in X attempts.”,其中X表示猜测的次数。如果用户猜错了,则输出“Too low. Try again.”或“Too high. Try again.”的提示信息,并在下一轮循环中继续等待用户的输入。