c++简易猜数游戏
时间: 2023-07-03 21:19:55 浏览: 118
好的,以下是一个简易的C++猜数游戏代码,供你参考:
```
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(0)); // 设置随机数种子
int number = rand() % 100 + 1; // 生成1~100之间的随机数
int guess;
int tries = 0;
bool win = false;
cout << "Welcome to the Guessing Game!" << endl;
cout << "I have a number between 1 and 100. Can you guess it?" << endl;
while (!win) {
cout << "Enter your guess: ";
cin >> guess;
tries++;
if (guess == number) {
win = true;
cout << "Congratulations! You guessed the number in " << tries << " tries." << endl;
} else if (guess < number) {
cout << "Too low. Try again." << endl;
} else {
cout << "Too high. Try again." << endl;
}
}
return 0;
}
```
这个代码实现了一个简单的C++猜数游戏。程序会生成一个1~100之间的随机数,并提示玩家输入猜测的数字。如果玩家猜中了,程序会宣布其获胜,并显示猜测次数。如果猜错了,程序会告诉玩家猜的数字是偏高还是偏低,并让玩家继续猜。程序会记录猜测次数,直到玩家猜中为止。
阅读全文