/*我们让计算机来做一个猜数游戏,这个数在【1,100】之间,我们选数的人只需告诉计算机它猜的数是大于,小于或等于正确的数
但当有恶意的用户会把数定在【1,100】之外,这时计算机就会做出防御识别出用户在欺骗它*/
#include<cstdlib>
#include<iostream>
#include<string>
using namespace std;
int main(){
cout<<"Think of a number between 1 and 100"<<endl
<<"I will make a guess;"
<<"tell me if I'm (H)igh or (L)ow"<<endl;
int low=1,high=100;
bool guessed=false;
while(!guessed){
//Invariant: the number is in range [1,100]
if(low>high){ //Invariant violation(违反)
cout<<"You cheated , I quited\n";
return EXIT_FAILURE;
}
int guess=(low+high)/2;
cout<<"My guess is "<< guess<<".";
cout<<"(H)igh, (L)ow , or (E)qual? ";
string response;
cin>>response;
switch(toupper(response[0])){
case 'H':
high=guess-1;
break;
case 'L':
low=guess+1;
break;
case 'E':
guessed=true;
break;
default:
cout<<"Invalid(无效) response"<<endl;
continue;
}
}
cout<<"I got it!"<<endl;
return EXIT_SUCCESS;
}