用C++写个小游戏代码
时间: 2023-09-04 15:13:06 浏览: 74
以下是一个简单的猜数字小游戏的代码,运行后会随机生成一个数字,玩家可以输入猜测的数字,程序会提示猜测的数字是大了还是小了,直到猜中为止。
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int num, guess, count = 0;
srand(time(NULL));
num = rand() % 100 + 1; // 生成1到100的随机数
printf("猜数字游戏,数字范围在1到100之间\n");
do {
printf("请输入你猜的数字:");
scanf("%d", &guess);
count++;
if (guess > num) {
printf("猜的数字太大了\n");
} else if (guess < num) {
printf("猜的数字太小了\n");
} else {
printf("恭喜你,猜中了!你用了%d次机会\n", count);
}
} while (guess != num);
return 0;
}
```
相关问题
用c++写一个小游戏代码
好的,这里给您提供一个简单的猜数字小游戏的C++代码:
```c++
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
// 随机种子
srand(time(0));
// 生成一个1-100之间的随机数
int answer = rand() % 100 + 1;
int guess = 0;
int numGuesses = 0;
cout << "欢迎来到猜数字游戏!\n\n";
while (guess != answer)
{
cout << "请输入您猜的数字(1-100):";
cin >> guess;
numGuesses++;
if (guess > answer)
{
cout << "猜测的数字太大了,请再试一次!\n\n";
}
else if (guess < answer)
{
cout << "猜测的数字太小了,请再试一次!\n\n";
}
else
{
cout << "\n恭喜您,猜对了!\n";
cout << "您一共猜了 " << numGuesses << " 次。\n";
}
}
return 0;
}
```
这个小游戏的规则是:程序会随机生成一个 1-100 之间的数字,玩家需要输入自己猜测的数字,程序会提示玩家猜测的数字是偏大还是偏小,直到玩家猜中为止。程序会统计玩家猜了多少次才猜中。
用c++做个小游戏 写出代码
以下是一个简单的猜数字游戏的C++代码:
```
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0)); // 初始化随机数种子
int secretNumber = rand() % 100 + 1; // 生成一个1到100之间的随机数
int guess = 0;
int tries = 0;
cout << "*** 猜数字游戏 ***" << endl;
do {
cout << "请猜一个1到100之间的数字: ";
cin >> guess;
tries++;
if (guess > secretNumber) {
cout << "太大了!" << endl;
} else if (guess < secretNumber) {
cout << "太小了!" << endl;
} else {
cout << "恭喜你,猜对了!" << endl;
cout << "你用了" << tries << "次猜对了这个数字。" << endl;
}
} while (guess != secretNumber);
return 0;
}
```
这个游戏会提示用户猜一个1到100之间的数字,然后根据用户输入的数字给出提示,直到用户猜对为止。在每次猜错时,程序会告诉用户猜的数字是太大了还是太小了。同时,程序还会记录用户猜的次数,并在用户猜对时输出猜对的次数。