c++猜数游戏代码

#include<bits/stdc++.h>
using namespace std;
int n,m;
int main(){
	srand(time(0));
	n=rand()%100+1;
	while(1){
		cout<<"请在1~100中选择一个数:";
		cin>>m;
		if(m==n){
			break;
		}
		else if(m<n){
			cout<<"猜小了";
		}
		else{
			cout<<"猜大了";
		}
		for(int i=1;i<=100000000;i++){
			cout<<"";
		}
		system("cls");	
	}
	cout<<"猜中了!";
	return 0;
}
3 个赞

#include
#include
#include

class Game {
public:
void play() {
srand(time(0));
int secretNumber = rand() % 100 + 1;
while (true) {
std::cout << "输入你的猜测(1-100): ";
int guess;
std::cin >> guess;
if (guess < secretNumber) {
std::cout << “猜测过低。\n”;
} else if (guess > secretNumber) {
std::cout << “猜测过高。\n”;
} else {
std::cout << “恭喜你,猜对了!\n”;
break;
}
}
}
};

int main() {
Game game;
game.play();
return 0;
}
(也可以这样写)

2 个赞

这样写有个问题,如果输入字符就会进入死循环

1 个赞

或者变量的值过大了

1 个赞