Вопрос задан 21.11.2023 в 12:45. Предмет Информатика. Спрашивает Mosejko Yurij.

С++ GuessException В этой задаче вам предстоит отгадать число, загаданное жюри. Жюри загадало

число от 1 до 100 включительно. Требуется отгадать его за неболее чем 30 попыток. А именно, есть объект типа BlackBox class BlackBox { public: void GuessNumber(int x) const; }; В этом объекте хранится число. У него есть единственный публичный метод GuessNumber. Этот объект будет передан вам по константной ссылке. Пусть жюри загадало число y от 1 до 100. Если вызвать метод GuessNumber у объекта BlackBox с аргументом x, то может произойти одна из 3 ситуаций: 1. y < x. Тогда будет брошено исключение типа ExceptionLess 2. y == x. Тогда будет брошено исключение типа ExceptionEqual 3. y > x. Тогда будет брошено исключение типа ExceptionGreater Все исключения будут подключены к вашему коду, а задаются они так: class ExceptionLess : public std::exception { }; class ExceptionGreater : public std::exception { }; class ExceptionEqual : public std::exception { }; Также к вашему коду будет добавлена реализация самого класса BlackBox, однако его код не раскрывается. Ваша задача написать функцию int guess(const BlackBox& box) Она принимает объект типа BlackBox, а возвращает загаданное число. У вас есть неболее 30 попыток, чтобы отгадать это число, иначе рещение получит вердикт RE В систему отправляйте лишь код функции guess и необходимые библиотеки, всё остальное будет подключено автоматически
0 0
Перейти к ответам

Ответы на вопрос

Внимание! Ответы на вопросы дают живые люди. Они могут содержать ошибочную информацию, заблуждения, а также ответы могут быть сгенерированы нейросетями. Будьте внимательны. Если вы уверены, что ответ неверный, нажмите кнопку "Пожаловаться" под ответом.
Отвечает Мигасюк Андрей.

Ответ:

int guess(const BlackBox& box) {

   int left = 1, right = 100;

   int middle;

   for (int i = 0; i < 30; ++i) {

       middle = (left + right) / 2;

       try {

           box.GuessNumber(middle);

           return middle;

       }

       catch (ExceptionLess& e) {

           right = middle - 1;

       }

       catch (ExceptionGreater& e) {

           left = middle + 1;

       }

       catch (ExceptionEqual& e) {

           return middle;

       }

   }

   throw std::runtime_error("Too many attempts");

}

Объяснение:

0 0
Отвечает нейросеть ChatGpt. Будьте внимательны, ответы нейросети могут содержать ошибочные или выдуманные данные.

To solve the GuessException problem, you need to write a function called `guess` that takes an object of type `BlackBox` as a parameter and returns the guessed number. The `BlackBox` object contains a hidden number, and you need to guess it within 30 attempts.

The `BlackBox` class has a single public method called `GuessNumber`, which takes an integer argument `x`. When you call the `GuessNumber` method with `x`, one of the following three situations can occur:

1. If the hidden number (`y`) is less than `x`, an exception of type `ExceptionLess` will be thrown. 2. If the hidden number (`y`) is equal to `x`, an exception of type `ExceptionEqual` will be thrown. 3. If the hidden number (`y`) is greater than `x`, an exception of type `ExceptionGreater` will be thrown.

Your task is to implement the `guess` function, which should return the guessed number. You have a maximum of 30 attempts to guess the number, otherwise, your solution will receive a verdict of "RE" (runtime error).

Here's an example implementation of the `guess` function:

```cpp int guess(const BlackBox& box) { int low = 1; int high = 100;

for (int i = 0; i < 30; i++) { int mid = (low + high) / 2;

try { box.GuessNumber(mid); return mid; // Guessed the number correctly } catch (const ExceptionLess&) { high = mid - 1; // Adjust the upper bound } catch (const ExceptionGreater&) { low = mid + 1; // Adjust the lower bound } catch (const ExceptionEqual&) { return mid; // Guessed the number correctly } }

// If the loop completes without returning, it means the number was not guessed within 30 attempts // Handle this case according to the problem requirements (e.g., return a special value or throw an exception) } ```

In this implementation, we use a binary search algorithm to guess the number efficiently. We start with a range from 1 to 100 (inclusive) and divide it in half on each iteration. We call the `GuessNumber` method with the midpoint of the range and handle the exceptions accordingly. If the exception is `ExceptionLess`, we adjust the upper bound of the range. If the exception is `ExceptionGreater`, we adjust the lower bound of the range. If the exception is `ExceptionEqual`, we have guessed the number correctly and return it.

Please note that the implementation of the `BlackBox` class is not provided, as its code is not disclosed. You only need to implement the `guess` function based on the given requirements.

Remember to submit only the code for the `guess` function and any necessary libraries. The rest of the code will be automatically included.

0 0

Похожие вопросы

Топ вопросов за вчера в категории Информатика

Последние заданные вопросы в категории Информатика

Задать вопрос