-
Notifications
You must be signed in to change notification settings - Fork 0
Tasks solutions #2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: master
Are you sure you want to change the base?
Conversation
…ссе (Task0 & Task1)
…ены изменения в задаче для нахождения среднего квадратов 3-х чисел.
…м расстояния между двумя окружностями (Task0)
UsovaMA
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Одно небольшое замечание на будущее.
| { | ||
| printf("Okrujnosti ne svyazani mejdu soboy\n"); | ||
| } | ||
| else ((d < r1 + r2) && (d + r1 > r2 || d + r2 > r1)); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Это условие избыточно, если мы до этого места дошли, то вариантов кроме как пересечения не остаётся.
|
Не увидела Task1 из HW, по нему тоже был дедлайн. |
…the entered number (2 methods)
|
@UsovaMA проверьте, пожалуйста, задание в классе 01.10.21 с инвертированием числа и подсчетом суммы цифр введенного числа (т.е. с 2-мя режимами) |
| case 1: | ||
| printf("Hello! Let's inverse the number!\n"); | ||
| printf("For exit - enter 0\n"); | ||
|
|
||
| while (isWork) { | ||
| int isError = 0; //������ ��� | ||
| do { | ||
| if (isError) printf("You entered the wrong number! Number must be positive! Try again, please.\n"); | ||
| printf("input positive number: "); | ||
| scanf_s("%d", &num1); | ||
|
|
||
| if (num1 == 0) { | ||
| isWork = 0; | ||
| break; //���������� �����, ����� �� ���� | ||
| } | ||
| isError = (num1 < 0); //������ ������ ������ | ||
| } while (isError); | ||
| if (!isWork) continue; //�� ��������� ������� ��������, ��������� � ��������� �������� | ||
| //����� ����� break, �� ������ ���� (����) while (1) { | ||
| //continue � ������ | ||
|
|
||
| //algorythm | ||
| long int c = 0; //c is an inverted number in result | ||
|
|
||
| while (num1) { | ||
| c *= 10; | ||
| c += num1 % 10; | ||
| num1 /= 10; | ||
| } | ||
| //result | ||
| printf("Result is %d\n", c); | ||
| } | ||
| printf("Goodbye!\n"); | ||
| break; |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Посмотри внимательно на case 1 и case 2. Мы в классе обсуждали проблему дублирования. Тут оно явное и сильное. В switch нужно брать только отличающиеся участки кода, то есть
switch (modeofthetask) {
case 1:
while (num) {
c *= 10;
c += num % 10;
num /= 10;
}
break;
case 2:
while (num) {
d += num % 10;
num /= 10;
}
break;
default:
printf("You entered the variant that doesn't exist! Try again, please.\n");
break;
}
Кода станет в 2 раза меньше.
|
@UsovaMA посмотрите, пожалуйста, задачу с инверсированием числа и суммой его чисел (2 метода). Исправил её. И у меня вопрос, я немного не понимаю. Как сделать так, чтобы пользователь сначала выбирал режим, а потом вводил число, т.е. такой же вариант как я сделал изначально, но без повторений участков кода ? Я вроде как залил Task2 из HW только что, его пока не смотрите, оно недоделано. Никитин Кирилл, 3821Б1ПР2 |
|
@UsovaMA посмотрите Task2 (Homework), пожалуйста. Сделал более менее нормально только первую часть, где пользователь отгадывает число. Сделал с "goto" пока что, но я переделаю, как надо. Вопрос: вообще не понимаю, как реализовать решение для второго режима, где компьютер угадывает число. Updated 09.10 И еще одна проблема: при вводе символов "<" или ">" программа странно работает. |
|
Решение по заданному вопросу, например, может быть следующим:
|
| printf("Welcome!\nYou gotta guess the number that the computer picked in range between 1 to 1000\n"); | ||
| srand(time(0)); | ||
| rand_num = 1 + rand() % 1000; //� ���� ������� �� ������� ��������� ������� rand() �� 1000 � ��������� 1, ����� ���������� ������ ��������, �.�. �� 1 �� 1000. | ||
| //printf("%d\n", c); //�����, ���������� ����������� | ||
| printf("The computer has picked the number in range of 1 to 1000!\nTry to guess it! Good luck!\nEnter the number You think the computer has picked: "); | ||
| again: | ||
| scanf_s("%d", &attempt); | ||
| while (attempt > 0) { | ||
| if ((attempt >= 1) && (attempt <= 1000)) { | ||
| if (attempt == rand_num) { | ||
| printf("\nCongratulations! You guessed the number!\nThe number for guessing was: %d\n", rand_num); | ||
| count_of_tries++; | ||
| break; | ||
| } | ||
| else | ||
| if (attempt > rand_num) { | ||
| printf("The number < %d, try again: ", attempt); | ||
| count_of_tries++; | ||
| goto again; | ||
| break; | ||
| } | ||
| else { | ||
| printf("The number > %d, try again: ", attempt); | ||
| count_of_tries++; | ||
| goto again; | ||
| break; | ||
| } | ||
| } | ||
| else { | ||
| printf("You entered the wrong number! The range is 1 to 1000.\nEnter the number again, please: "); | ||
| goto again; | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
printf("Welcome!\nYou gotta guess the number that the computer picked in range between 1 to 1000\n");
srand(time(0));
rand_num = 1 + rand() % 1000;
printf("The computer has picked the number in range of 1 to 1000!\nTry to guess it! Good luck!\nEnter the number You think the computer has picked: ");
int notGuessed = 1;
while (notGuessed) {
scanf_s("%d", &attempt);
if ((attempt >= 1) && (attempt <= 1000)) {
if (attempt == rand_num) {
printf("\nCongratulations! You guessed the number!\nThe number for guessing was: %d\n", rand_num);
count_of_tries++;
notGuessed = 0;
break;
}
else if (attempt > rand_num) {
printf("The number < %d, try again: ", attempt);
count_of_tries++;
} else {
printf("The number > %d, try again: ", attempt);
count_of_tries++;
}
} else {
printf("You entered the wrong number! The range is 1 to 1000.\nEnter the number again, please: ");
}
}
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Добавляем вечный внешний цикл с загадыванием числа и вердиктом. Внутри правильного ответа меняем флаг цикла на ложь, чтобы он закончился. Никаких goto
| while ((num_for_guess >= 1) && (num_for_guess <=1000)) { | ||
| current = (left + right) / 2; | ||
| printf("\nComputer thinks this number is %d\nIs it right?\n", current); | ||
| scanf_s("%c", &compare, 1); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
ЧТО???
scanf_s("%c", &compare, 1); ????
", 1"???
Это что такое откуда зачем почему что значит вообще в твоём понимании?
| case 2: | ||
| printf("Welcome!\nThe computer will try to guess the number that you'd pick for guessing\n"); | ||
| printf("Choose the number from 1 to 1000: "); | ||
| scanf_s("%d", &num_for_guess); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
По смыслу тут ввод не нужен. Как игра выглядит для пользователя:
Здравствуйте, загадайте число, я его отгадаю!)
Загадали?
Это... 500?
<
Хмм... меньше 500... 250?
>
Хмм... больше 250... 375?
<
Хмм... меньше 375... 250?
>
Хмм... больше 250... 312?
=
Ура! Бинго.
Нигде в консоли пользователь не вводит числа. Компьютер угадывает число деля отрезок пополам (это оптимальная выигрышная стратегия). На последней итерации в примере отрезок от 250 до 375.
Если мы по нашему алгоритму придём к тому, что отрезок от N до N И при этом N не ответ - пишем пользователю, что он нас обманул и с обманщиками мы не играем.
|
Все ответы и подсказки дала |
|
@UsovaMA у меня проблема с инициализацией массива динамического |
|
@UsovaMA я вроде как сделал задание примерно, как нужно, но код не работает идеально. Никитин Кирилл, 3821Б1ПР |
|
@UsovaMA посмотрите, пожалуйста, task 4 (terminal class) В чем отличия след. пунктов ? (с пары последней не запомнил): |
|
@UsovaMA доделал таск 1 из д.з., должен был убрать магические числа и добавить в проверку eps. |

@UsovaMA проверьте, пожалуйста, решения задач с ведьмаком и нахождением расстояния между двумя окружностями.
Извините, что задержался на полчаса, тем самым отправив не в срок. У меня тут все поломалось и пришлось создавать новую ветку и т.д. (Простите мне эти полчаса, пожалуйста) )