想玩猜数游戏吗,up给你一个吧
以下是单机版的:
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
std::srand(std::time(0)); // 用当前时间初始化随机数生成器
int secretNumber = std::rand() % 100 + 1; // 生成1到100之间的随机数
int guess = 0;
int attempts = 0;
std::cout << "欢迎来到猜数字游戏!" << std::endl;
std::cout << "我已经想好了一个1到100之间的数字。" << std::endl;
while (guess != secretNumber) {
std::cout << "请输入你的猜测: ";
std::cin >> guess;
attempts++;
if (guess > secretNumber) {
std::cout << "太大了! 再试一次." << std::endl;
} else if (guess < secretNumber) {
std::cout << "太小了! 再试一次." << std::endl;
} else {
std::cout << "恭喜你! 你猜对了数字 " << secretNumber << "!" << std::endl;
std::cout << "你总共猜了 " << attempts << " 次." << std::endl;
}
}
return 0;
}
这个是联机双人版的:
#include <bits/stdc++.h>
using namespace std;
int main() {
int n, ta, tb, a, b;
srand((unsigned)time(NULL));
ta = rand() % 1000 + 1;
tb = rand() % 1000 + 1;
while (a != ta && b != tb) {
cout << "请玩家A输入一个整数(1~1000):";
cin >> a;
cout << "请玩家B输入一个整数(1~1000):";
cin >> b;
if (a > ta) {
cout << "玩家A猜大了!" << endl;
} else if (a < ta) {
cout << "玩家A猜小了!" << endl;
}
if (b > tb) {
cout << "玩家B猜大了!" << endl;
} else if (b < tb) {
cout << "玩家B猜小了!" << endl;
}
}
if (a == ta && b == tb) {
cout << "恭喜玩家A/B都猜对了 平局!" << endl;
} else if (a == ta) {
cout << "恭喜玩家A获胜";
} else if (b == tb) {
cout << "恭喜玩家B获胜";
}
return 0;
}