具体案例示例
1. 猜数字游戏
这个游戏会随机生成一个1到100之间的数字,玩家需要通过猜测来找到这个数字。每次猜测后,程序会告诉玩家猜的数字是太大了还是太小了,直到玩家猜中为止。
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
std::srand(std::time(0)); // 生成随机数种子
int number = std::rand() % 100 + 1; // 生成1到100之间的随机数
int guess = 0;
int attempts = 0;
std::cout << "欢迎来到猜数字游戏!" << std::endl;
std::cout << "我已经想好了一个1到100之间的数字,你能猜到它是什么吗?" << std::endl;
while (guess != number) {
std::cout << "请输入你的猜测:";
std::cin >> guess;
attempts++;