写一个猜数字游戏的c++代码
时间: 2023-04-06 12:00:25 浏览: 79
好的,我可以回答这个问题。以下是一个简单的猜数字游戏的 C 代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int guess, num, count = 0;
srand(time(0)); // 用当前时间作为随机数种子
num = rand() % 100 + 1; // 生成 1 到 100 之间的随机数
printf("猜数字游戏开始!\n");
do {
printf("请输入一个 1 到 100 之间的整数:");
scanf("%d", &guess);
count++; // 猜测次数加 1
if (guess > num) {
printf("太大了,再试一次!\n");
} else if (guess < num) {
printf("太小了,再试一次!\n");
} else {
printf("恭喜你,猜对了!你一共猜了 %d 次。\n", count);
}
} while (guess != num);
return 0;
}
相关问题
请用C++写一个猜数字游戏
好的,请看下面的代码:
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
srand(time(0)); // 设置随机数种子,确保每次运行程序时生成的随机数不同
int number = rand() % 100 + 1; // 生成 1~100 之间的随机整数
int guess;
cout << "我想了一个 1~100 之间的数字,你猜是多少?" << endl;
do {
cout << "请输入你猜的数字:";
cin >> guess;
if (guess < number) {
cout << "你猜的数字太小了,再试试!" << endl;
} else if (guess > number) {
cout << "你猜的数字太大了,再试试!" << endl;
} else {
cout << "恭喜你,猜对了!你真聪明!" << endl;
}
} while (guess != number);
return 0;
}
```
这是一个简单的猜数字游戏,程序会生成一个 1~100 之间的随机整数,然后让玩家猜这个数字是多少。如果猜的数字太小了,程序会提示“你猜的数字太小了,再试试!”;如果猜的数字太大了,程序会提示“你猜的数字太大了,再试试!”;如果猜对了,程序会提示“恭喜你,猜对了!你真聪明!”
编写一个猜数字游戏c++
以下是一个简单的猜数字游戏的C ++代码:
```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; // 猜测次数
cout << "猜数字游戏" << endl << endl;
do {
cout << "请输入一个1到100之间的整数: ";
cin >> guess;
tries++;
if (guess > number) {
cout << "猜大了!" << endl << endl;
} else if (guess < number) {
cout << "猜小了!" << endl << endl;
} else {
cout << endl << "恭喜你猜对了!" << endl;
cout << "你猜了" << tries << "次。" << endl;
}
} while (guess != number);
return 0;
}
```
运行程序后,将随机生成一个1到100之间的整数,然后要求玩家输入一个猜测数字,程序会根据玩家的猜测提示是猜大了还是猜小了,直到猜对为止。在每次猜测后,都会显示已经猜测的次数。