---
# System prepended metadata

title: Guess Number

---

# Guess Number
https://neoj.sprout.tw/problem/148/
### 問題敘述
請完成下列的程式碼，對於每次的遊戲，不得使用less()超過15次，其中你要猜的數字的範圍為1 ~ 100。

若你認為答案是x，請呼叫guess(x);。

Note : 請勿在你要寫的程式中使用到less_counter與target_number，這可能會造成你的程式錯誤，也請別額外include其他東西。
```cpp
#include <cstdio>
#include <cstdlib>

int target_number;
int less_counter = 0;
int less(int guess_num){
  less_counter++;
  if (less_counter > 15)
    printf("You guess too many times ...\n");
  if (target_number < guess_num)
    return 1;
  else
    return 0;
}

void guess(int guess_num){
  if (guess_num == target_number)
    printf("Correct!\n");
  else
    printf("Not correct! Q__Q\n");
}

int main(){
  while (scanf("%d", &target_number) != EOF)
  { /* input a number between [1,101)*/
    less_counter = 0;

    /*
        請在此寫你的程式碼
    */

  }


  return 0;
}
```
### Hint
請上傳如下列的程式碼
```cpp
int L = 1;
int R = 101;
int ans = 0;
for (int i = L + 1; i < R; i++)
  if (less(i) == 1 && less(i - 1) == 0)
  {
    ans = i;
    break;
  }
}
```
guess(ans);
此程式碼有兩個錯誤:
+ 呼叫less()次數過多
+ 找到的答案是錯的

# Code
```cpp
int min_num = 0, max_num = 100,
    guess_num = 0, mi = 0, ma = 0;
  while (true)
  {
    guess_num = (max_num + min_num) / 2;
    mi = less(guess_num);
    ma = less(guess_num + 1);
    if (mi == 0 && ma == 1)
    {
      guess(guess_num);
      break;
    }
    if (mi == 1)
      max_num = guess_num - 1;
    else
      min_num = guess_num + 1;
  }
```