交互題 : 1. Guess the Number(二分)

交互題 : 1. Guess the Number(二分)

題目傳送門

題意:給定1------1e6的範圍的一個數,要你在規定次數內猜出該數。

思路:
在這裏插入圖片描述
AC代碼:

#include<bits/stdc++.h>
using namespace std;
int main(){
	int l=1,r=1e6;
	while(l!=r){
		int mid=(l+r+1)>>1;//這裏要用(l+r+1) 因爲是跟"<"和">="比較,如果l=mid ans=r=l+1 則會一直循環. 
		printf("%d\n",mid);
		fflush(stdout);
		char c[3];
		scanf("%s",c);
		if(strcmp(c,"<")) r=mid-1;
		else l=mid;
	}
	printf("! %d\n",l);
	fflush(stdout);
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章