F
F
flash_back2016-02-07 15:56:39
C++ / C#
flash_back, 2016-02-07 15:56:39

An exercise from Stroustrup's book. Guess the number program. Can you write better?

Hello.
I did an exercise for Bjarne Stroustrup's book "Programming. Principles and practice
of using C++".
The text of the exercise is:

Write a program to guess the number. The user must think
of a number from 1 to 100, and the program must ask questions to find out what
number he has thought of (for example, "Thought number less than 50"). Your program
should be able to identify the number after no more than seven tries. Hint
: use the < and <= operators and if-else constructs.

My solution is:
#include <iostream>

using namespace std;

int main()
{
  setlocale(LC_ALL, "Russian");
  double curr =50;
  double shift =50;
  char answer = ' ';
  bool equal_check = false;
  for(int i=0;i<8;i++){
    cout << "Число равно" << static_cast<int>(curr + 0.5) <<"?(y,n)";
    cin >> answer;
    if (answer=='y') { equal_check = true; break; }
    cout << "Число меньше " <<  static_cast<int>(curr + 0.5) << "?(y,n)";
    cin >> answer;
    cout << "shift" << shift << endl;
    cout << "curr" << curr << endl;
    if (answer=='y') { shift=shift/2; curr -= shift; } 
    else if(answer=='n') { shift=shift/2; curr += shift; } 
  }
  if (!equal_check)
  {
    cout << "wrong input" << endl;
  }
  system("pause");
  return 0;
}

It seems to work, but there is a suspicion that I did not fully understand the essence of the exercise and what else can be written in a simpler and more efficient way. Can you please tell me how to write better? And did I understand the problem correctly?
upd. In short, he seems to have found a solution that fits the conditions of the exercise:
#include <iostream>

using namespace std;

int main()
{
  setlocale(LC_ALL, "Russian");
  double curr =50, shift =50;
  char answer = ' ';
  cout << "Загадайте число от 1 до 100." << endl;
  system("pause");
  for(int i=0;i<8;i++){
    cout << "Число меньше " <<  static_cast<int>(curr + 0.5) << "?(y,n)";
    cin >> answer;
    if (answer=='y'){ 
      shift=shift/2; 
      curr -= shift; 
    } 
    else if(answer=='n'){ 
      shift=shift/2; 
      curr += shift; 
    }
    if ( (curr <= 1.0) || (curr >= 99.5) ){ 
      cout <<"Ваше число " <<  static_cast<int>(curr + 0.5) << endl; 
      break;
    };
    if ( shift <= 0.5){ 
      cout <<"Ваше число  " <<  static_cast<int>(curr) << endl; 
      break;
    }
  }
  system("pause");
  return 0;
}

upd. I rechecked again.
It also turned out to be a bug. Doesn't work for 99. Looked through for the first time.
Corrected, it stopped working as a solution from below from teugen in the second option (when choosing 100, it does not reach 100).
As a result, it turns out that with the original question “The intended number is less than X”, if you do not change it and include 100 in the possible choice of number, and not take from 1 to 99 , there will be no way to work in seven iterations with the option 100, but only in eight . Therefore, I am inclined to believe that the text of the question has an incorrect translation into Russian and it was assumed that the interval will be from 1 to 99. Or the second option is such that the question (“The intended number is less than X”) can be modified and then a variant such as that of teugen turned out to be third time (final). I personally think that all the same, the translator’s mistake or Bjorn wrote inaccurately and it was expected that the interval would be from 1 to 99.
I think what implementation was meant (the solution from teugen in the second version, slightly corrected by me):
#include <iostream>
#include <cmath>

using namespace std;

int main()
{
  setlocale(LC_ALL, "Russian");

  int min = 1, max = 100;
  cout << "Загадайте число от " << min << " до " << (max - 1) << ".\n";  //микрофикс

  int guess = (max + min) / 2, count = 7;//микрофикс (C++98)
  for (int i = 0; i < count; ++i)
  {
    cout << "Загаданное число меньше " << guess << "? (y/n)\n";

    char ans;
    cin >> ans;
    if (ans == 'y')
    {
      max = guess;
    }
    else
    {
      min = guess;
    }
    guess = (min + max) / 2;

    if (max - min < 2)
    {
      cout << "Вы загадали число \"" << guess << "\".\n";
      system("PAUSE");
      return 0;
    }
  }

  cout << "Жулик!\n";
  system("PAUSE");
  return 0;
}

I think the issue is closed.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
teugen, 2016-02-07
@flash_back

Understood correctly, this is an ordinary binary search. It is usually implemented recursively, you can look at the implementation, for example, on Wikipedia .
You can also write better - with line breaks and spaces it will look much nicer.
Ps You have 8 loop passes.
upd. If we assume that every question (no matter what) is an attempt, then we can limit ourselves to only seven questions. For example, like this:

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    setlocale(LC_ALL, "Russian");

    int min = 1, max = 100;
    cout << "Загадайте число от " << min << " до " << max << ".\n";

    int guess = (min + max) / 2, count = (int) ceil(std::log2(max - min));
    for (int i = 0; i < count; ++i)
    {
        cout << "Загаданное число меньше или равно " << guess << "? (y/n)\n";   // fixed

        char ans;
        cin >> ans;
        if (ans == 'y')
        {
            max = guess;
        }
        else
        {
            min = guess + 1;    // fixed
        }
        guess = (min + max) / 2;

        if (max == min)    // fixed
        {
            cout << "Вы загадали число \"" << guess << "\".\n";
            system("PAUSE");
            return 0;
        }
    }

    cout << "Жулик!\n";
    system("PAUSE");
    return 0;
}

M
maaGames, 2016-02-07
@maaGames

Most likely it is meant that the user must enter a number, and then the program "looks" for it without interacting with the user.
In your solution, the comparison to less is replaced by communication with the user.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question