Пакет: bc

Версия
7.0.3
Релиз
1.niceos5
Архитектура
x86_64
Хэш GOST
74a93e7bb1f49a170e660142eb60336a49d0417025dc4ec67d25853660731bbc
Хэш MD5
d57b5ea946b96fa60b3096723de2d135
Хэш SHA256
bee2749158a4049a280bccd9df749dcaceb09347e6b0bf670bd06050574c2c3e
Лицензия
GPLv2+
Дата сборки
12 мая 2025 г.
Размер
275,411 МиБ
Совместимые ОС
rpm файл:
bc-7.0.3-1.niceos5.x86_64.rpm
Зависимости
Имя Тип Версия
flex runtime -
libc.so.6()(64bit) runtime -
libc.so.6(GLIBC_2.14)(64bit) runtime -
libc.so.6(GLIBC_2.2.5)(64bit) runtime -
libc.so.6(GLIBC_2.3)(64bit) runtime -
libc.so.6(GLIBC_2.33)(64bit) runtime -
libc.so.6(GLIBC_2.34)(64bit) runtime -
libc.so.6(GLIBC_2.4)(64bit) runtime -
libreadline.so.8()(64bit) runtime -
rtld(GNU_HASH) runtime -
Граф зависимостей
История изменений
Дата Автор Сообщение
31 мар. 2025 г. Stanislav Belikov <sbelikov@ncsgp.ru> Первая сборка для bc
Файлы пакета
      • /usr/bin/bc 194,5 КиБ
      • /usr/bin/dc 2 Б
          • /usr/share/locale/de_AT.UTF-8/bc 17 Б
          • /usr/share/locale/de_CH.UTF-8/bc 17 Б
          • /usr/share/locale/de_DE.UTF-8/bc 4,251 КиБ
          • /usr/share/locale/en_AU.UTF-8/bc 11 Б
          • /usr/share/locale/en_CA.UTF-8/bc 11 Б
          • /usr/share/locale/en_GB.UTF-8/bc 11 Б
          • /usr/share/locale/en_IE.UTF-8/bc 11 Б
          • /usr/share/locale/en_NZ.UTF-8/bc 11 Б
          • /usr/share/locale/en_US.UTF-8/bc 11 Б
          • /usr/share/locale/en_US/bc 3,91 КиБ
          • /usr/share/locale/es_ES.UTF-8/bc 4,394 КиБ
          • /usr/share/locale/fr_BE.UTF-8/bc 17 Б
          • /usr/share/locale/fr_CA.UTF-8/bc 17 Б
          • /usr/share/locale/fr_CH.UTF-8/bc 17 Б
          • /usr/share/locale/fr_FR.UTF-8/bc 4,326 КиБ
          • /usr/share/locale/ja_JP.UTF-8/bc 4,649 КиБ
          • /usr/share/locale/nl_NL.UTF-8/bc 4,094 КиБ
          • /usr/share/locale/pl_PL.UTF-8/bc 4,284 КиБ
          • /usr/share/locale/pt_BR.UTF-8/bc 17 Б
          • /usr/share/locale/pt_PT.UTF-8/bc 4,259 КиБ
          • /usr/share/locale/ru_RU.CP1251/bc 36 Б
          • /usr/share/locale/ru_RU.KOI8-R/bc 36 Б
          • /usr/share/locale/ru_RU.UTF-8/bc 5,908 КиБ
          • /usr/share/locale/zh_CN.GB18030/bc 36 Б
          • /usr/share/locale/zh_CN.GB2312/bc 36 Б
          • /usr/share/locale/zh_CN.GBK/bc 36 Б
          • /usr/share/locale/zh_CN.UTF-8/bc 3,662 КиБ
          • /usr/share/man/man1/bc.1.gz 22,262 КиБ
          • /usr/share/man/man1/dc.1.gz 14,57 КиБ
Документация (man-страницы)

DC(1)			    General Commands Manual			 DC(1)



Name
       dc - калькулятор с произвольной точностью для десятичных вычислений в обратной польской нотации

SYNOPSIS
       dc [-cChiPRvVx] [--version] [--help] [--digit-clamp] [--no-digit-clamp]
       [--interactive] [--no-prompt] [--no-read-prompt] [--extended-register]
       [-e expr] [--expression=expr...]	 [-f file...]  [--file=file...]
       [file...]  [-I ibase] [--ibase=ibase] [-O obase] [--obase=obase] [-S
       scale] [--scale=scale] [-E seed] [--seed=seed]

DESCRIPTION
       dc(1) является калькулятором с произвольной точностью. Он использует стек (обратная польская нотация) для хранения чисел и результатов вычислений.
       Арифметические операции извлекают аргументы из стека и помещают результаты обратно.

       Если файлы не указаны в командной строке, то dc(1) читает из stdin (см. раздел STDIN). В противном случае, эти файлы обрабатываются, и
       dc(1) завершает работу.

       Если пользователь хочет настроить стандартную среду, он может использовать DC_ENV_ARGS (см. раздел ENVIRONMENT VARIABLES). Например, если
       пользователь хочет всегда устанавливать scale равным 10, он может установить DC_ENV_ARGS в -e 10k, и этот dc(1) будет всегда запускаться с
       scale равным 10.

OPTIONS
       Ниже перечислены опции, поддерживаемые dc(1).

       -C, --no-digit-clamp
	      Отключает фиксацию цифр, больших или равных текущему ibase, при анализе чисел.

	      Это означает, что значение, добавляемое к числу от цифры, всегда равно значению этой цифры, умноженному на значение ibase, возведённое в
	      степень позиции цифры, которая начинается с 0 от наименее значимой цифры.

	      Если эта опция и/или опции -c или --digit-clamp указаны несколько раз, используется последняя.

	      Эта опция переопределяет переменную среды DC_DIGIT_CLAMP (см. раздел ENVIRONMENT VARIABLES) и значение по умолчанию, которое можно
	      запросить с опциями -h или --help.

	      Это нестандартное расширение.

       -c, --digit-clamp
	      Включает фиксацию цифр, больших или равных текущему ibase, при анализе чисел.

	      Это означает, что для цифр, значение которых больше или равно ibase, добавляемое к числу значение равно (ibase минус 1), умноженному на
	      значение ibase, возведённое в степень позиции цифры, которая начинается с 0 от наименее значимой цифры.

	      Если эта опция и/или опции -C или --no-digit-clamp указаны несколько раз, используется последняя.

	      Эта опция переопределяет переменную среды DC_DIGIT_CLAMP (см. раздел ENVIRONMENT VARIABLES) и значение по умолчанию, которое можно
	      запросить с опциями -h или --help.

	      Это нестандартное расширение.

       -E seed, --seed=seed
	      Устанавливает встроенную переменную seed в значение seed, предполагая, что seed находится в базе 10. Это фатальная ошибка, если seed не
	      является допустимым числом.

	      Если несколько экземпляров этой опции указаны, используется последняя.

	      Это нестандартное расширение.

       -e expr, --expression=expr
	      Вычисляет expr. Если несколько выражений указаны, они вычисляются в порядке. Если файлы также указаны (см. ниже), выражения и файлы
	      вычисляются в порядке указания. Это означает, что если файл указан перед выражением, файл читается и вычисляется первым.

	      Если эта опция указана в командной строке (т.е. не в DC_ENV_ARGS, см. раздел ENVIRONMENT VARIABLES), то после обработки всех выражений и
	      файлов dc(1) завершит работу, если - (stdin) не был указан хотя бы один раз в -f или --file, в командной строке или в DC_ENV_ARGS.
	      Однако, если другие аргументы -e, --expression, -f или --file указаны после -f- или эквивалентного, dc(1) выдаст фатальную ошибку и
	      выйдет.

	      Это нестандартное расширение.

       -f file, --file=file
	      Читает файл и вычисляет его построчно, как будто он был прочитан из stdin. Если выражения также указаны (см. выше), выражения
	      вычисляются в порядке указания.

	      Если эта опция указана в командной строке (т.е. не в DC_ENV_ARGS, см. раздел ENVIRONMENT VARIABLES), то после обработки всех выражений и
	      файлов dc(1) завершит работу, если - (stdin) не был указан хотя бы один раз в -f или --file. Однако, если другие аргументы -e,
	      --expression, -f или --file указаны после -f- или эквивалентного, dc(1) выдаст фатальную ошибку и выйдет.

	      Это нестандартное расширение.

       -h, --help
	      Выводит сообщение использования и выходит.

       -I ibase, --ibase=ibase
	      Устанавливает встроенную переменную ibase в значение ibase, предполагая, что ibase находится в базе 10. Это фатальная ошибка, если
	      ibase не является допустимым числом.

	      Если несколько экземпляров этой опции указаны, используется последняя.

	      Это нестандартное расширение.

       -i, --interactive
	      Принудительно включает интерактивный режим. (См. раздел INTERACTIVE MODE.)

	      Это нестандартное расширение.

       -L, --no-line-length
	      Отключает проверку длины строки и выводит числа без обратных слэшей и новых строк. Другими словами, эта опция устанавливает
	      BC_LINE_LENGTH в 0 (см. раздел ENVIRONMENT VARIABLES).

	      Это нестандартное расширение.

       -O obase, --obase=obase
	      Устанавливает встроенную переменную obase в значение obase, предполагая, что obase находится в базе 10. Это фатальная ошибка, если
	      obase не является допустимым числом.

	      Если несколько экземпляров этой опции указаны, используется последняя.

	      Это нестандартное расширение.

       -P, --no-prompt
	      Отключает подсказку в режиме TTY. (Подсказка включается только в режиме TTY. См. раздел TTY MODE.) Это в основном для пользователей,
	      которые не хотят подсказку или не привыкли к ней в dc(1). Большинство таких пользователей захотят добавить эту опцию в DC_ENV_ARGS.

	      Эти опции переопределяют переменные среды DC_PROMPT и DC_TTY_MODE (см. раздел ENVIRONMENT VARIABLES).

	      Это нестандартное расширение.

       -R, --no-read-prompt
	      Отключает подсказку чтения в режиме TTY. (Подсказка чтения включается только в режиме TTY. См. раздел TTY MODE.) Это в основном для
	      пользователей, которые не хотят подсказку чтения или не привыкли к ней в dc(1). Большинство таких пользователей захотят добавить эту
	      опцию в BC_ENV_ARGS (см. раздел ENVIRONMENT VARIABLES). Эта опция также полезна в строках hash bang скриптов dc(1), которые запрашивают
	      ввод от пользователя.

	      Эта опция не отключает обычную подсказку, потому что подсказка чтения используется только при команде ?.

	      Эти опции переопределяют переменные среды DC_PROMPT и DC_TTY_MODE (см. раздел ENVIRONMENT VARIABLES), но только для подсказки чтения.

	      Это нестандартное расширение.

       -S scale, --scale=scale
	      Устанавливает встроенную переменную scale в значение scale, предполагая, что scale находится в базе 10. Это фатальная ошибка, если
	      scale не является допустимым числом.

	      Если несколько экземпляров этой опции указаны, используется последняя.

	      Это нестандартное расширение.

       -v, -V, --version
	      Выводит информацию о версии (заголовок авторских прав) и выходит.

       -x --extended-register
	      Включает расширенный режим регистров. См. подраздел Extended Register Mode в разделе REGISTERS для дополнительной информации.

	      Это нестандартное расширение.

       -z, --leading-zeroes
	      Делает так, чтобы dc(1) выводил все числа больше -1 и меньше 1, и не равные 0, с ведущим нулем.

	      Это нестандартное расширение.

       Все длинные опции являются нестандартными расширениями.

STDIN
       Если файлы не указаны в командной строке и никакие файлы или выражения не указаны с опциями -f, --file, -e или --expression, то dc(1) читает из
       stdin.

       Однако, есть нюанс.

       Во-первых, stdin оценивается построчно. Единственное исключение — если строка завершена, но не закончена. Это означает, что, кроме экранированных
       скобок, все скобки должны быть сбалансированы перед тем, как dc(1) анализирует и выполняет.

STDOUT
       Любые неошибочные выводы записываются в stdout. Кроме того, если история (см. раздел HISTORY) и подсказка (см. раздел TTY MODE) включены, они
       также выводятся в stdout.

       Примечание: В отличие от других реализаций dc(1), этот dc(1) выдаст фатальную ошибку (см. раздел EXIT STATUS), если не может записать в stdout,
       так что если stdout закрыт, как в dc >&-, он завершит работу с ошибкой. Это сделано, чтобы dc(1) мог сообщать о проблемах, когда stdout
       перенаправлен в файл.

       Если есть скрипты, зависящие от поведения других реализаций dc(1), рекомендуется изменить эти скрипты, чтобы перенаправлять stdout в /dev/null.

STDERR
       Любые сообщения об ошибках записываются в stderr.

       Примечание: В отличие от других реализаций dc(1), этот dc(1) выдаст фатальную ошибку (см. раздел EXIT STATUS), если не может записать в stderr,
       так что если stderr закрыт, как в dc 2>&-, он завершит работу с ошибкой. Это сделано, чтобы dc(1) мог завершиться с кодом ошибки, когда stderr
       перенаправлен в файл.

       Если есть скрипты, зависящие от поведения других реализаций dc(1), рекомендуется изменить эти скрипты, чтобы перенаправлять stderr в /dev/null.

SYNTAX
       Каждый элемент в исходном коде ввода, либо число (см. раздел NUMBERS), либо команда (см. раздел COMMANDS), обрабатывается и выполняется в
       порядке. Ввод обрабатывается немедленно после ввода.

       ibase — это регистр (см. раздел REGISTERS), который определяет, как интерпретировать константные числа. Это "входная" база, или числовая база,
       используемая для интерпретации входных чисел. ibase изначально равна 10. Максимальное допустимое значение для ibase — 16. Минимальное
       допустимое значение для ibase — 2. Максимальное допустимое значение для ibase можно запросить в программах dc(1) с командой T.

       obase — это регистр (см. раздел REGISTERS), который определяет, как выводить результаты. Это "выходная" база, или числовая база, используемая
       для вывода чисел. obase изначально равна 10. Максимальное допустимое значение для obase — DC_BASE_MAX и его можно запросить с командой U.
       Минимальное допустимое значение для obase — 0. Если obase равна 0, значения выводятся в научной нотации, а если obase равна 1, значения
       выводятся в инженерной нотации. В противном случае, значения выводятся в указанной базе.

       Вывод в научной и инженерной нотациях являются нестандартными расширениями.

       Масштаб выражения — это количество цифр в результате выражения справа от десятичной точки, а scale — регистр (см. раздел REGISTERS), который
       устанавливает точность любых операций (с исключениями). scale изначально равна 0. scale не может быть отрицательной. Максимальное допустимое
       значение для scale можно запросить в программах dc(1) с командой V.

       seed — регистр, содержащий текущее значение для генератора псевдослучайных чисел. Если текущее значение seed запрошено и сохранено, то если
       оно присвоено seed позже, генератор псевдослучайных чисел гарантированно произведёт ту же последовательность псевдослучайных чисел, которая
       была сгенерирована после первого запроса значения seed.

       Несколько значений, присвоенных seed, могут производить одну и ту же последовательность псевдослучайных чисел. Аналогично, когда значение
       присваивается seed, не гарантируется, что немедленный запрос seed вернёт то же значение. Кроме того, значение seed изменится после любого
       вызова команды ' или “, которая не получает значение 0 или 1. Максимальное целое число, возвращаемое командой ', можно запросить с командой W.

       Примечание: Значения, возвращаемые генератором псевдослучайных чисел с командами ' и “, гарантированно НЕ являются криптографически
       безопасными. Это следствие использования генератора псевдослучайных чисел с seed. Однако, они гарантированно воспроизводимы с одинаковыми
       значениями seed. Это означает, что псевдослучайные значения из dc(1) должны использоваться только в случаях, где воспроизводимая последовательность
       псевдослучайных чисел КРИТИЧЕСКИ важна. В других случаях используйте генератор псевдослучайных чисел без seed.

       Генератор псевдослучайных чисел, seed и все связанные операции являются нестандартными расширениями.

   Comments
       Комментарии идут от # до, но не включая, следующей новой строки. Это нестандартное расширение.

NUMBERS
       Числа — это строки, состоящие из цифр, заглавных букв до F и максимум одной точки для основания. Числа могут иметь до DC_NUM_MAX цифр.
       Заглавные буквы равны 9 плюс их позиция в алфавите (т.е., A равна 10, или 9+1).

       Если цифра или буква не имеет смысла с текущим значением ibase (т.е., они больше или равны текущему значению ibase), то поведение зависит от
       наличия опций -c/--digit-clamp или -C/--no-digit-clamp (см. раздел OPTIONS), наличия и настройки переменной среды DC_DIGIT_CLAMP (см. раздел
       ENVIRONMENT VARIABLES) или значения по умолчанию, которое можно запросить с опциями -h/--help.

       Если фиксация выключена, то цифры или буквы, большие или равные текущему значению ibase, не изменяются. Вместо этого, их значение умножается на
       соответствующую степень ibase и добавляется в число. Это означает, что с ibase равным 3, число AB равно 3^1*A+3^0*B, что равно 3 раза 10 плюс
       11, или 41.

       Если фиксация включена, то цифры или буквы, большие или равные текущему значению ibase, устанавливаются в значение самой высокой допустимой
       цифры в ibase перед умножением на соответствующую степень ibase и добавлением в число. Это означает, что с ibase равным 3, число AB равно
       3^1*2+3^0*2, что равно 3 раза 2 плюс 2, или 8.

       Есть одно исключение из фиксации: однозначные числа (т.е., A в одиночку). Такие числа никогда не фиксируются и всегда принимают значение, которое
       они имели бы в самой высокой возможной ibase. Это означает, что A в одиночку всегда равно десятичному 10, а Z — десятичному 35. Это поведение
       предписано стандартом для bc(1) (см. раздел STANDARDS) и предназначено для простого способа установки текущего ibase (с командой i) независимо
       от текущего значения ibase.

       Если фиксация включена и требуется зафиксированное значение символа, используйте ведущий ноль, т.е. для A используйте 0A.

       Кроме того, dc(1) принимает числа в научной нотации. Они имеют форму <number>e<integer>. Показатель (часть после e) должен быть целым числом.
       Пример: 1.89237e9, что равно 1892370000. Отрицательные показатели также разрешены, так что 4.2890e_3 равно 0.0042890.

       ПРЕДУПРЕЖДЕНИЕ: Как число, так и показатель в научной нотации интерпретируются в соответствии с текущим ibase, но число всё равно умножается на
       10^показатель независимо от текущего ibase. Например, если ibase равна 16 и dc(1) получает строку FFeA, результирующее десятичное число будет
       2550000000000, а если dc(1) получает строку 10e_4, результирующее десятичное число будет 0.0016.

       Принятие ввода в научной нотации является нестандартным расширением.

COMMANDS
       Допустимые команды перечислены ниже.

   Printing
       Эти команды используются для вывода.

       Обратите внимание, что для вывода чисел доступны научная нотация и инженерная нотация. Научная нотация активируется присвоением 0 obase с
       помощью 0o, а инженерная нотация — присвоением 1 obase с помощью 1o. Чтобы деактивировать их, просто присвойте другое значение obase.

       Вывод чисел в научной и/или инженерной нотациях является нестандартным расширением.

       p      Выводит значение на вершине стека, будь то число или строка, и выводит новую строку после.

	      Это не изменяет стек.

       n      Выводит значение на вершине стека, будь то число или строка, и извлекает его из стека.

       P      Извлекает значение из стека.

	      Если значение — число, оно усекается, и абсолютное значение результата выводится, как будто obase равна 256, и каждая цифра
	      интерпретируется как 8-битный символ ASCII, делая его потоком байтов.

	      Если значение — строка, она выводится без завершающей новой строки.

	      Это нестандартное расширение.

       f      Выводит всё содержимое стека, в порядке от самого нового к самому старому, без изменений.

	      Пользователи должны использовать эту команду, когда они запутались.

   Arithmetic
       Это команды, используемые для арифметики.

       +      Извлекает два верхних значения из стека, складывает их и помещает результат в стек. Масштаб результата равен максимальному масштабу
	      обоих операндов.

       -      Извлекает два верхних значения из стека, вычитает их и помещает результат в стек. Масштаб результата равен максимальному масштабу
	      обоих операндов.

       *      Извлекает два верхних значения из стека, умножает их и помещает результат в стек. Если a — масштаб первого выражения, а b — масштаб
	      второго выражения, то масштаб результата равен min(a+b, max(scale, a, b)), где min() и max() возвращают очевидные значения.

       /      Извлекает два верхних значения из стека, делит их и помещает результат в стек. Масштаб результата равен scale.

	      Первое извлечённое значение из стека должно быть ненулевым.

       %      Извлекает два верхних значения из стека, вычисляет остаток и помещает результат в стек.

	      Вычисление остатка эквивалентно 1) вычислению a/b с текущим масштабом и 2) использованию результата шага 1 для расчёта a-(a/b)*b с
	      масштабом max(scale+scale(b), scale(a)).

	      Первое извлечённое значение из стека должно быть ненулевым.

       ~      Извлекает два верхних значения из стека, делит и вычисляет остаток, и помещает результаты (делённое сначала, остаток вторым) в стек.
	      Это эквивалентно x y / x y %, кроме того, что x и y оцениваются только один раз.

	      Первое извлечённое значение из стека должно быть ненулевым.

	      Это нестандартное расширение.

       ^      Извлекает два верхних значения из стека, возводит второе в степень первого и помещает результат в стек. Масштаб результата равен
	      scale.

	      Первое извлечённое значение из стека должно быть целым числом, и если это значение отрицательное, второе извлечённое значение из стека
	      должно быть ненулевым.

       v      Извлекает верхнее значение из стека, вычисляет его квадратный корень и помещает результат в стек. Масштаб результата равен scale.

	      Значение, извлечённое из стека, должно быть неотрицательным.

       _      Если эта команда непосредственно предшествует числу (т.е. без пробелов или других команд), то это число вводится как отрицательное.

	      В противном случае, верхнее значение в стеке извлекается и копируется, а копия отрицается и помещается в стек. Это поведение без числа
	      является нестандартным расширением.

       b      Извлекает верхнее значение из стека и, если оно нулевое, помещает его обратно в стек. В противном случае, его абсолютное значение
	      помещается в стек.

	      Это нестандартное расширение.

       |      Извлекает три верхних значения из стека, вычисляет модульное возведение в степень и помещает результат в стек.

	      Первое извлечённое значение используется как модуль сокращения и должно быть целым числом и ненулевым. Второе извлечённое значение
	      используется как показатель и должно быть целым числом и неотрицательным. Третье извлечённое значение — основание и должно быть
	      целым числом.

	      Это нестандартное расширение.

       $      Извлекает верхнее значение из стека и копирует его, а копия усекается и помещается в стек.

	      Это нестандартное расширение.

       @      Извлекает два верхних значения из стека и устанавливает точность второго в значение первого, путём усечения или расширения.

	      Первое извлечённое значение из стека должно быть целым числом и неотрицательным.

	      Это нестандартное расширение.

       H      Извлекает два верхних значения из стека и сдвигаet второе влево (основание сдвигается вправо) на значение первого.

	      Первое извлечённое значение из стека должно быть целым числом и неотрицательным.

	      Это нестандартное расширение.

       h      Извлекает два верхних значения из стека и сдвигаet второе вправо (основание сдвигается влево) на значение первого.

	      Первое извлечённое значение из стека должно быть целым числом и неотрицательным.

	      Это нестандартное расширение.

       G      Извлекает два верхних значения из стека, сравнивает их и помещает 1, если они равны, или 0 в противном случае.

	      Это нестандартное расширение.

       N      Извлекает верхнее значение из стека и помещает 1, если оно равно 0; в противном случае помещает 0.

	      Это нестандартное расширение.

       (      Извлекает два верхних значения из стека, сравнивает их и помещает 1, если первое меньше второго, или 0 в противном случае.

	      Это нестандартное расширение.

       {      Извлекает два верхних значения из стека, сравнивает их и помещает 1, если первое меньше или равно второму, или 0 в противном случае.

	      Это нестандартное расширение.

       )      Извлекает два верхних значения из стека, сравнивает их и помещает 1, если первое больше второго, или 0 в противном случае.

	      Это нестандартное расширение.

       }      Извлекает два верхних значения из стека, сравнивает их и помещает 1, если первое больше или равно второму, или 0 в противном случае.

	      Это нестандартное расширение.

       M      Извлекает два верхних значения из стека. Если оба ненулевые, помещает 1 в стек. Если любое из них нулевое или оба нулевые, то
	      помещает 0 в стек.

	      Это аналогично оператору && в bc(1) и не является оператором короткого замыкания.

	      Это нестандартное расширение.

       m      Извлекает два верхних значения из стека. Если хотя бы одно из них ненулевое, помещает 1 в стек. Если оба нулевые, то помещает 0 в
	      стек.

	      Это аналогично оператору || в bc(1) и не является оператором короткого замыкания.

	      Это нестандартное расширение.

   Pseudo-Random Number Generator
       dc(1) имеет встроенный генератор псевдослучайных чисел. Эти команды запрашивают генератор псевдослучайных чисел. (См. Параметры для дополнительной
       информации о значении seed, которое управляет генератором псевдослучайных чисел.)

       Генератор псевдослучайных чисел гарантированно НЕ является криптографически безопасным.

       ’      Генерирует целое число между 0 и DC_RAND_MAX, включительно (см. раздел LIMITS).

	      Сгенерированное целое число делается как можно более беспристрастным, с учётом ограничений генератора псевдослучайных чисел.

	      Это нестандартное расширение.

       “      Извлекает значение из стека, которое используется как исключительная верхняя граница для генерируемого целого числа. Если граница
	      отрицательная или не является целым числом, возникает ошибка, и dc(1) сбрасывается (см. раздел RESET), в то время как seed остаётся
	      неизменным. Если граница больше DC_RAND_MAX, более высокая граница учитывается путём генерации нескольких псевдослучайных целых чисел,
	      умножения их на соответствующие степени DC_RAND_MAX+1 и сложения. Таким образом, размер генерируемого целого числа не ограничен.
	      Использование этой команды изменит значение seed, если операнд не 0 или 1. В этом случае помещается 0 в стек, и seed не изменяется.

	      Сгенерированное целое число делается как можно более беспристрастным, с учётом ограничений генератора псевдослучайных чисел.

	      Это нестандартное расширение.

   Stack Control
       Эти команды управляют стеком.

       c      Удаляет все элементы из стека ("очищает" стек).

       d      Копирует элемент на вершине стека ("дублирует") и помещает копию в стек.

       r      Меняет местами ("разворачивает") два верхних элемента стека.

       R      Извлекает ("удаляет") верхнее значение из стека.

   Register Control
       Эти команды управляют регистрами (см. раздел REGISTERS).

       sr     Извлекает значение с вершины стека и сохраняет его в регистре r.

       lr     Копирует значение в регистре r и помещает его в стек. Это не изменяет содержимое r.

       Sr     Извлекает значение с вершины (основного) стека и помещает его в стек регистра r. Предыдущее значение регистра становится недоступным.

       Lr     Извлекает значение с вершины стека регистра r и помещает его в основной стек. Предыдущее значение в стеке регистра r, если оно есть,
	      теперь доступно через команду lr.

   Parameters
       Эти команды управляют значениями ibase, obase, scale и seed. Также см. раздел SYNTAX.

       i      Извлекает значение с вершины стека и использует его для установки ibase, которая должна быть между 2 и 16, включительно.

	      Если значение на вершине стека имеет масштаб, масштаб игнорируется.

       o      Извлекает значение с вершины стека и использует его для установки obase, которая должна быть между 0 и DC_BASE_MAX, включительно (см.
	      раздел LIMITS и раздел NUMBERS).

	      Если значение на вершине стека имеет масштаб, масштаб игнорируется.

       k      Извлекает значение с вершины стека и использует его для установки scale, которая должна быть неотрицательной.

	      Если значение на вершине стека имеет масштаб, масштаб игнорируется.

       j      Извлекает значение с вершины стека и использует его для установки seed. Значение seed зависит от текущего генератора псевдослучайных
	      чисел, но гарантированно не изменится, кроме как в новых основных версиях.

	      Масштаб и знак значения могут быть значимыми.

	      Если ранее использованное значение seed используется снова, генератор псевдослучайных чисел гарантированно произведёт ту же
	      последовательность псевдослучайных чисел, что и при предыдущем использовании значения seed.

	      Точное значение, присвоенное seed, не гарантируется, что будет возвращено при использовании команды J. Однако, если seed возвращает
	      другое значение, оба значения, когда присвоены seed, гарантированно произведут ту же последовательность псевдослучайных чисел. Это
	      означает, что определённые значения, присвоенные seed, не произведут уникальных последовательностей псевдослучайных чисел.

	      Нет ограничения на длину (количество значимых десятичных цифр) или масштаб значения, которое может быть присвоено seed.

	      Это нестандартное расширение.

       I      Помещает текущее значение ibase в основной стек.

       O      Помещает текущее значение obase в основной стек.

       K      Помещает текущее значение scale в основной стек.

       J      Помещает текущее значение seed в основной стек.

	      Это нестандартное расширение.

       T      Помещает максимальное допустимое значение ibase в основной стек.

	      Это нестандартное расширение.

       U      Помещает максимальное допустимое значение obase в основной стек.

	      Это нестандартное расширение.

       V      Помещает максимальное допустимое значение scale в основной стек.

	      Это нестандартное расширение.

       W      Помещает максимальное (включительно) целое число, которое может быть сгенерировано командой ' генератора псевдослучайных чисел.

	      Это нестандартное расширение.

   Strings
       Следующие команды управляют строками.

       dc(1) может работать с числами и строками, а регистры (см. раздел REGISTERS) могут содержать как строки, так и числа. dc(1) всегда знает,
       содержат ли содержимое регистра строку или число.

       Хотя арифметические операции требуют чисел и выдадут ошибку, если получат строку, другие команды принимают строки.

       Строки также могут выполняться как макросы. Например, если строка [1pR] выполняется как макрос, то код 1pR выполняется, что означает, что 1
       будет выведено с новой строкой после и затем извлечено из стека.

       [characters]
	      Создаёт строку, содержащую characters, и помещает её в стек.

	      Если в строке есть скобки ([ и ]), то они должны быть сбалансированы. Несбалансированные скобки можно экранировать с помощью символа
	      обратной косой черты (\).

	      Если в строке есть символ обратной косой черты, символ после него (даже другая обратная косая черта) помещается в строку как есть, но
	      (первая) обратная косая черта не помещается.

       a      Извлекает значение с вершины стека.

	      Если это число, оно усекается и берётся его абсолютное значение. Результат mod 256 вычисляется. Если результат равен 0, помещается
	      пустая строка; в противном случае, помещается строка из одного символа, где символ — результат mod, интерпретированный как символ ASCII.

	      Если это строка, то создаётся новая строка. Если исходная строка пуста, новая строка пуста. Если нет, то первый символ исходной строки
	      используется для создания новой строки как строки из одного символа. Новая строка затем помещается в стек.

	      Это нестандартное расширение.

       x      Извлекает значение с вершины стека.

	      Если это число, оно помещается обратно в стек.

	      Если это строка, она выполняется как макрос.

	      Это поведение стандартно при выполнении любого макроса, будь то этой командой или условными командами выполнения ниже.

       >r     Извлекает два значения из стека, которые должны быть числами, и сравнивает их. Если первое значение больше второго, то содержимое
	      регистра r выполняется.

	      Например, 0 1>a выполнит содержимое регистра a, а 1 0>a — нет.

	      Если любое или оба значения не являются числами, dc(1) выдаст ошибку и сбросится (см. раздел RESET).

       >res   Как выше, но выполнит регистр s, если сравнение не проходит.

	      Если любое или оба значения не являются числами, dc(1) выдаст ошибку и сбросится (см. раздел RESET).

	      Это нестандартное расширение.

       !>r    Извлекает два значения из стека, которые должны быть числами, и сравнивает их. Если первое значение не больше второго (меньше или
	      равно), то содержимое регистра r выполняется.

	      Если любое или оба значения не являются числами, dc(1) выдаст ошибку и сбросится (см. раздел RESET).

       !>res  Как выше, но выполнит регистр s, если сравнение не проходит.

	      Если любое или оба значения не являются числами, dc(1) выдаст ошибку и сбросится (см. раздел RESET).

	      Это нестандартное расширение.

       <r     Извлекает два значения из стека, которые должны быть числами, и сравнивает их. Если первое значение меньше второго, то содержимое
	      регистра r выполняется.

	      Если любое или оба значения не являются числами, dc(1) выдаст ошибку и сбросится (см. раздел RESET).

       <res   Как выше, но выполнит регистр s, если сравнение не проходит.

	      Если любое или оба значения не являются числами, dc(1) выдаст ошибку и сбросится (см. раздел RESET).

	      Это нестандартное расширение.

       !<r    Извлекает два значения из стека, которые должны быть числами, и сравнивает их. Если первое значение не меньше второго (больше или
	      равно), то содержимое регистра r выполняется.

	      Если любое или оба значения не являются числами, dc(1) выдаст ошибку и сбросится (см. раздел RESET).

       !<res  Как выше, но выполнит регистр s, если сравнение не проходит.

	      Если любое или оба значения не являются числами, dc(1) выдаст ошибку и сбросится (см. раздел RESET).

	      Это нестандартное расширение.

       =r     Извлекает два значения из стека, которые должны быть числами, и сравнивает их. Если первое значение равно второму, то содержимое
	      регистра r выполняется.

	      Если любое или оба значения не являются числами, dc(1) выдаст ошибку и сбросится (см. раздел RESET).

       =res   Как выше, но выполнит регистр s, если сравнение не проходит.

	      Если любое или оба значения не являются числами, dc(1) выдаст ошибку и сбросится (см. раздел RESET).

	      Это нестандартное расширение.

       !=r    Извлекает два значения из стека, которые должны быть числами, и сравнивает их. Если первое значение не равно второму, то содержимое
	      регистра r выполняется.

	      Если любое или оба значения не являются числами, dc(1) выдаст ошибку и сбросится (см. раздел RESET).

       !=res  Как выше, но выполнит регистр s, если сравнение не проходит.

	      Если любое или оба значения не являются числами, dc(1) выдаст ошибку и сбросится (см. раздел RESET).

	      Это нестандартное расширение.

       ?      Читает строку из stdin и выполняет её. Это позволяет макросам запрашивать ввод от пользователей.

       q      Во время выполнения макроса это выходит из выполнения этого макроса и макроса, который его выполнил. Если макросов нет или выполняется
	      только один макрос, dc(1) выходит.

       Q      Извлекает значение из стека, которое должно быть неотрицательным, и используется как количество выполнений макросов для извлечения из
	      стека выполнения. Если количество уровней для извлечения больше, чем количество выполняемых макросов, dc(1) выходит.

       ,      Помещает глубину стека выполнения в стек. Стек выполнения — это стек выполнения строк. Число, помещаемое в стек, ровно столько, сколько
	      нужно, чтобы заставить dc(1) выйти с командой Q, так что последовательность ,Q заставит dc(1) выйти.

	      Это нестандартное расширение.

   Status
       Эти команды запрашивают статус стека или его верхнего значения.

       Z      Извлекает значение из стека.

	      Если это число, вычисляет количество значимых десятичных цифр и помещает результат. Оно поместит 1, если аргумент равен 0 без
	      десятичных мест.

	      Если это строка, помещает количество символов в строке.

       X      Извлекает значение из стека.

	      Если это число, помещает масштаб значения в стек.

	      Если это строка, помещает 0.

       u      Извлекает одно значение из стека. Если значение — число, это помещает 1 в стек. В противном случае (если это строка), помещает 0.

	      Это нестандартное расширение.

       t      Извлекает одно значение из стека. Если значение — строка, это помещает 1 в стек. В противном случае (если это число), помещает 0.

	      Это нестандартное расширение.

       z      Помещает текущую глубину стека (до выполнения этой команды) в стек.

       yr     Помещает текущую глубину стека регистра r в основной стек.

	      Поскольку каждый регистр имеет глубину 1 (с значением 0 в верхнем элементе) при запуске dc(1), dc(1) требует, чтобы стек каждого
	      регистра всегда имел хотя бы один элемент; dc(1) выдаст ошибку и сбросится в противном случае (см. раздел RESET). Это означает, что эта
	      команда никогда не помещает 0.

	      Это нестандартное расширение.

   Arrays
       Эти команды манипулируют массивами.

       :r     Извлекает два верхних значения из стека. Второе значение будет сохранено в массиве r (см. раздел REGISTERS), индексированном первым
	      значением.

       ;r     Извлекает значение с вершины стека и использует его как индекс в массиве r. Выбранное значение затем помещается в стек.

       Yr     Помещает длину массива r в стек.

	      Это нестандартное расширение.

   Global Settings
       Эти команды извлекают глобальные настройки. Это единственные команды, которые требуют нескольких конкретных символов, и все они начинаются с
       буквы g. Только символы ниже разрешены после символа g; любой другой символ вызывает ошибку разбора (см. раздел ERRORS).

       gl     Помещает длину строки, установленную DC_LINE_LENGTH (см. раздел ENVIRONMENT VARIABLES), в стек.

       gx     Помещает 1 в стек, если включён расширенный режим регистров, или 0 в противном случае. См. подраздел Extended Register Mode в разделе
	      REGISTERS для дополнительной информации.

       gz     Помещает 0 в стек, если настройка ведущих нулей не включена с опциями -z или --leading-zeroes (см. раздел OPTIONS), или ненулевое
	      значение в противном случае.

REGISTERS
       Регистры — это имена, которые могут хранить строки, числа и массивы. (Регистры для чисел/строк не мешают регистрам для массивов.)

       Каждый регистр также является своим стеком, так что текущее значение регистра — это вершина стека для регистра. Все регистры, при первом
       обращении, имеют одно значение (0) в своем стеке, и это ошибка времени выполнения, если попытаться извлечь этот элемент из стека регистра.

       В нерасширенном режиме регистров имя регистра — это просто одиночный символ, следующий за любой командой, которая нуждается в имени регистра.
       Единственные исключения: новая строка (`\n') и левая скобка (`['); это ошибка разбора, если новая строка или левая скобка используются как имя
       регистра.

   Extended Register Mode
       В отличие от большинства других реализаций dc(1), этот dc(1) предоставляет почти неограниченное количество регистров, если включён расширенный
       режим регистров.

       Если включён расширенный режим регистров (опции -x или --extended-register указаны в командной строке), то нормальные одиночные регистры
       используются, если символ, следующий сразу за командой, нуждающейся в имени регистра, — это пробел (согласно isspace()) и не новая строка
       (`\n').

       В этом случае имя регистра находится в соответствии с регулярным выражением [a-z][a-z0-9_]*, и это ошибка разбора, если следующие
       непробельные символы не соответствуют этому регулярному выражению.

RESET
       Когда dc(1) встречает ошибку или сигнал, для которого у него есть ненулевой обработчик, он сбрасывается. Это означает, что несколько вещей
       происходит.

       Во-первых, любые макросы, которые выполняются, останавливаются и извлекаются из стека выполнения. Поведение похоже на исключения в языках
       программирования. Затем точка выполнения устанавливается так, чтобы любой код, ожидающий выполнения (после возврата всех макросов), был
       пропущен.

       Однако, стек значений не очищается; в интерактивном режиме пользователи могут инспектировать стек и манипулировать им.

       Таким образом, когда dc(1) сбрасывается, он пропускает любой оставшийся код, ожидающий выполнения. Затем, если это интерактивный режим и
       ошибка не была фатальной (см. раздел EXIT STATUS), он запрашивает дополнительный ввод; в противном случае, он выходит с соответствующим кодом
       возврата.

PERFORMANCE
       Большинство реализаций dc(1) используют типы char для расчёта значения 1 десятичной цифры за раз, но это может быть медленно. Этот dc(1) делает
       по-другому.

       Он использует большие целые числа для расчёта более чем 1 десятичной цифры за раз. Если построен в среде, где DC_LONG_BIT (см. раздел LIMITS)
       равна 64, то каждое целое число имеет 9 десятичных цифр. Если построен в среде, где DC_LONG_BIT равна 32, то каждое целое число имеет 4
       десятичных цифры. Это значение (количество десятичных цифр на большое целое число) называется DC_BASE_DIGS.

       Кроме того, этот dc(1) использует ещё большее целое число для проверки переполнения. Этот тип целого числа зависит от значения DC_LONG_BIT, но
       всегда как минимум в два раза больше, чем тип целого числа, используемый для хранения цифр.

LIMITS
       Ниже приведены ограничения dc(1):

       DC_LONG_BIT
	      Количество бит в типе long в среде, где построен dc(1). Это определяет, сколько десятичных цифр может храниться в одном большом целом
	      числе (см. раздел PERFORMANCE).

       DC_BASE_DIGS
	      Количество десятичных цифр на большое целое число (см. раздел PERFORMANCE). Зависит от DC_LONG_BIT.

       DC_BASE_POW
	      Максимальное десятичное число, которое каждое большое целое число может хранить (см. DC_BASE_DIGS), плюс 1. Зависит от DC_BASE_DIGS.

       DC_OVERFLOW_MAX
	      Максимальное число, которое тип переполнения может хранить (см. раздел PERFORMANCE). Зависит от DC_LONG_BIT.

       DC_BASE_MAX
	      Максимальная выходная база. Установлено как DC_BASE_POW.

       DC_DIM_MAX
	      Максимальный размер массивов. Установлено как SIZE_MAX-1.

       DC_SCALE_MAX
	      Максимальный масштаб. Установлено как DC_OVERFLOW_MAX-1.

       DC_STRING_MAX
	      Максимальная длина строк. Установлено как DC_OVERFLOW_MAX-1.

       DC_NAME_MAX
	      Максимальная длина идентификаторов. Установлено как DC_OVERFLOW_MAX-1.

       DC_NUM_MAX
	      Максимальная длина числа (в десятичных цифрах), включая цифры после десятичной точки. Установлено как DC_OVERFLOW_MAX-1.

       DC_RAND_MAX
	      Максимальное целое число (включительно), возвращаемое командой '. Установлено как 2^DC_LONG_BIT-1.

       Exponent
	      Максимально допустимый показатель (положительный или отрицательный). Установлено как DC_OVERFLOW_MAX.

       Number of vars
	      Максимальное количество переменных/массивов. Установлено как SIZE_MAX-1.

       Эти ограничения предназначены для того, чтобы быть эффективно несуществующими; ограничения настолько велики (хотя бы на 64-битных
       машинах), что они не должны стать проблемой. Фактически, память должна исчерпаться раньше, чем эти ограничения будут достигнуты.

ENVIRONMENT VARIABLES
       Как нестандартные расширения, dc(1) распознаёт следующие переменные среды:

       DC_ENV_ARGS
	      Это ещё один способ передать аргументы командной строки dc(1). Они должны быть в том же формате, что и все другие аргументы командной
	      строки. Они всегда обрабатываются первыми, так что файлы, указанные в DC_ENV_ARGS, будут обработаны перед аргументами и файлами,
	      указанными в командной строке. Это даёт пользователю возможность настроить "стандартные" опции и файлы для использования при каждом
	      запуске. Самое полезное, что такие файлы могут содержать, — это полезные функции, которые пользователь может захотеть каждый раз при
	      запуске dc(1). Другое использование — использование опции -e для установки scale в значение, отличное от 0.

	      Код, парсящий DC_ENV_ARGS, правильно обрабатывает кавыченные аргументы, но не понимает последовательности экранирования. Например,
	      строка “/home/gavin/some dc file.dc” будет правильно разобрана, но строка “/home/gavin/some "dc" file.dc” включит обратные слэши.

	      Разбор кавычек будет обрабатывать любой вид кавычек, ' или “. Таким образом, если у вас есть файл с любым количеством одинарных кавычек
	      в имени, вы можете использовать двойные кавычки как внешние, как в “some `dc' file.dc”, и наоборот, если у вас есть файл с двойными
	      кавычками. Однако, обработка файла с обоими видами кавычек в DC_ENV_ARGS не поддерживается из-за сложности разбора, хотя такие файлы
	      всё ещё поддерживаются в командной строке, где разбор выполняется оболочкой.

       DC_LINE_LENGTH
	      Если эта переменная среды существует и содержит целое число, большее 1 и меньшее UINT16_MAX (2^16-1), dc(1) будет выводить строки этой
	      длины, включая комбо обратной косой черты и новой строки. Длина строки по умолчанию — 70.

	      Специальное значение 0 отключит проверку длины строки и выведет числа без учёта длины строки и без обратных слэшей и новых строк.

       DC_SIGINT_RESET
	      Если dc(1) не в интерактивном режиме (см. раздел INTERACTIVE MODE), то эта переменная среды не имеет эффекта, потому что dc(1) выходит
	      при SIGINT, когда не в интерактивном режиме.

	      Однако, когда dc(1) в интерактивном режиме, то если эта переменная среды существует и содержит целое число, ненулевое значение
	      заставит dc(1) сбрасываться при SIGINT, а не выходить, и нулевое значение заставит dc(1) выйти. Если эта переменная среды существует и
	      не является целым числом, то dc(1) выйдет при SIGINT.

	      Эта переменная среды переопределяет значение по умолчанию, которое можно запросить с опциями -h или --help.

       DC_TTY_MODE
	      Если режим TTY недоступен (см. раздел TTY MODE), то эта переменная среды не имеет эффекта.

	      Однако, когда режим TTY доступен, то если эта переменная среды существует и содержит целое число, ненулевое значение заставит dc(1)
	      использовать режим TTY, а нулевое значение — нет.

	      Эта переменная среды переопределяет значение по умолчанию, которое можно запросить с опциями -h или --help.

       DC_PROMPT
	      Если режим TTY недоступен (см. раздел TTY MODE), то эта переменная среды не имеет эффекта.

	      Однако, когда режим TTY доступен, то если эта переменная среды существует и содержит целое число, ненулевое значение заставит dc(1)
	      использовать подсказку, а нулевое или нецелое значение — нет. Если эта переменная среды не существует, а DC_TTY_MODE существует, то
	      используется значение переменной DC_TTY_MODE.

	      Эта переменная среды и переменная DC_TTY_MODE переопределяют значение по умолчанию, которое можно запросить с опциями -h или --help.

       DC_EXPR_EXIT
	      Если любые выражения или файлы выражений указаны в командной строке с -e, --expression, -f или --file, то если эта переменная среды
	      существует и содержит целое число, ненулевое значение заставит dc(1) выйти после выполнения выражений и файлов выражений, а нулевое
	      значение — нет.

	      Эта переменная среды переопределяет значение по умолчанию, которое можно запросить с опциями -h или --help.

       DC_DIGIT_CLAMP
	      При анализе чисел, если эта переменная среды существует и содержит целое число, ненулевое значение заставит dc(1) фиксировать цифры,
	      большие или равные текущему ibase, так что все такие цифры считаются равными ibase минус 1, а нулевое значение отключит такую фиксацию,
	      так что эти цифры всегда равны своему значению, которое умножается на степень ibase.

	      Это никогда не применяется к однозначным числам, в соответствии со стандартом bc(1) (см. раздел STANDARDS).

	      Эта переменная среды переопределяет значение по умолчанию, которое можно запросить с опциями -h или --help.

EXIT STATUS
       dc(1) возвращает следующие коды выхода:

       0      Нет ошибки.

       1      Произошла математическая ошибка. Это следует стандартной практике использования 1 для ожидаемых ошибок, поскольку математические ошибки
	      будут происходить в процессе нормального выполнения.

	      Математические ошибки включают деление на 0, извлечение квадратного корня из отрицательного числа, использование отрицательного числа
	      как границы для генератора псевдослучайных чисел, попытку преобразования отрицательного числа в аппаратное целое, переполнение при
	      преобразовании числа в аппаратное целое, переполнение при расчёте размера числа и попытку операции, когда стек имеет слишком мало
	      элементов.

	      Преобразование в аппаратное целое происходит для второго операнда операторов возведения в степень (^), places (@), сдвига влево (H) и
	      сдвига вправо (h).

       2      Произошла ошибка разбора.

	      Ошибки разбора включают неожиданный EOF, использование недопустимого символа, неудачу в нахождении конца строки или комментария и
	      использование токена, где он недопустим.

       3      Произошла ошибка времени выполнения.

	      Ошибки времени выполнения включают присвоение недопустимого числа любому глобальному (ibase, obase или scale), передачу плохого
	      выражения вызову read(), вызов read() внутри read(), ошибки типов (включая попытку выполнения числа) и попытку операции, когда стек
	      имеет слишком мало элементов.

       4      Произошла фатальная ошибка.

	      Фатальные ошибки включают ошибки выделения памяти, ошибки ввода/вывода, неудачу в открытии файлов, попытку использования файлов, которые
	      не содержат только символы ASCII (dc(1) принимает только символы ASCII), попытку открытия директории как файла и указание недопустимых
	      опций командной строки.

       Код выхода 4 особый; при фатальной ошибке dc(1) всегда выходит и возвращает 4, независимо от режима dc(1).

       Другие статусы будут возвращены только когда dc(1) не в интерактивном режиме (см. раздел INTERACTIVE MODE), поскольку dc(1) сбрасывает своё
       состояние (см. раздел RESET) и принимает дополнительный ввод, когда такая ошибка происходит в интерактивном режиме. Это также относится к
       случаю, когда интерактивный режим принудительно включён флагом -i или опцией --interactive.

       Эти коды выхода позволяют использовать dc(1) в сценариях оболочки с проверкой ошибок, и нормальное поведение может быть принудительно
       включено с помощью флага -i или опции --interactive.

INTERACTIVE MODE
       Как и bc(1), dc(1) имеет интерактивный режим и неинтерактивный режим. Интерактивный режим включается автоматически, когда stdin и stdout
       подключены к терминалу, но флаг -i или опция --interactive могут включить его в других ситуациях.

       В интерактивном режиме dc(1) пытается восстановиться от ошибок (см. раздел RESET), и при нормальном выполнении сбрасывает stdout сразу после
       выполнения для текущего ввода. dc(1) также может сбрасываться при SIGINT вместо выхода, в зависимости от содержимого или значения по умолчанию
       переменной среды DC_SIGINT_RESET (см. раздел ENVIRONMENT VARIABLES).

TTY MODE
       Если stdin, stdout и stderr все подключены к TTY, то "режим TTY" считается доступным, и таким образом, dc(1) может включить режим TTY, в
       зависимости от некоторых настроек.

       Если переменная среды DC_TTY_MODE существует в среде (см. раздел ENVIRONMENT VARIABLES), то если эта переменная содержит ненулевое целое число,
       dc(1) включит режим TTY, когда stdin, stdout и stderr подключены к TTY. Если DC_TTY_MODE существует, но не является ненулевым целым числом, то
       dc(1) не включит режим TTY.

       Если переменная среды DC_TTY_MODE не существует, используется значение по умолчанию. Значение по умолчанию можно запросить с опциями -h или
       --help.

       Режим TTY отличается от интерактивного режима, потому что интерактивный режим требуется в спецификации bc(1) (см. раздел STANDARDS), и
       интерактивный режим требует только подключения stdin и stdout к терминалу.

   Command-Line History
       История командной строки включается только если доступен режим TTY (см. раздел TTY MODE), то есть, когда stdin, stdout и stderr подключены к
       TTY. См. раздел COMMAND LINE HISTORY для дополнительной информации.

   Prompt
       Если режим TTY доступен, то подсказку можно включить. Как и сам режим TTY, её можно включить или выключить с переменной среды DC_PROMPT (см.
       раздел ENVIRONMENT VARIABLES).

       Если переменная среды DC_PROMPT существует и является ненулевым целым числом, то подсказка включится, когда stdin, stdout и stderr подключены к
       TTY, и опции -P и --no-prompt не использовались. Подсказка чтения включится при тех же условиях, кроме того, что опции -R и --no-read-prompt не
       использовались.

       Однако, если DC_PROMPT не существует, подсказку можно включить или выключить с переменной среды DC_TTY_MODE, опциями -P и --no-prompt, и опциями
       -R и --no-read-prompt. См. разделы ENVIRONMENT VARIABLES и OPTIONS для дополнительных деталей.

SIGNAL HANDLING
       Отправка SIGINT заставит dc(1) сделать одну из двух вещей.

       Если dc(1) не в интерактивном режиме (см. раздел INTERACTIVE MODE), или переменная DC_SIGINT_RESET (см. раздел ENVIRONMENT VARIABLES), или её
       значение по умолчанию, либо не является целым числом, либо равно нулю, dc(1) выйдет.

       Однако, если dc(1) в интерактивном режиме, и DC_SIGINT_RESET или её значение по умолчанию является целым числом и ненулевым, то dc(1) остановит
       выполнение текущего ввода и сбросится (см. раздел RESET) при получении SIGINT.

       Обратите внимание, что "текущий ввод" может означать одну из двух вещей. Если dc(1) обрабатывает ввод из stdin в интерактивном режиме, он
       запросит дополнительный ввод. Если dc(1) обрабатывает ввод из файла в интерактивном режиме, он остановит обработку файла и начнёт обработку
       следующего файла, если он существует, или запросит ввод из stdin, если другого файла нет.

       Это означает, что если SIGINT отправлен dc(1) во время выполнения файла, может показаться, что dc(1) не отреагировал на сигнал, поскольку он
       немедленно начнёт выполнять следующий файл. Это по замыслу; большинство файлов, которые пользователи выполняют при взаимодействии с dc(1),
       содержат определения функций, которые быстро разбираются. Если файл занимает много времени на выполнение, в нём может быть ошибка. Остальные
       файлы всё ещё могут быть выполнены без проблем, позволяя пользователю продолжить.

       SIGTERM и SIGQUIT заставляют dc(1) очистить и выйти, а для всех других сигналов используется обработчик по умолчанию. Единственное исключение
       — SIGHUP; в этом случае и только когда dc(1) в режиме TTY (см. раздел TTY MODE), SIGHUP заставит dc(1) очистить и выйти.

COMMAND LINE HISTORY
       dc(1) поддерживает интерактивное редактирование командной строки.

       Если dc(1) может быть в режиме TTY (см. раздел TTY MODE), историю можно включить. Это означает, что история командной строки может быть включена
       только когда stdin, stdout и stderr подключены к TTY.

       Как и сам режим TTY, её можно включить или выключить с переменной среды DC_TTY_MODE (см. раздел ENVIRONMENT VARIABLES).

       Примечание: табы преобразуются в 8 пробелов.

LOCALES
       Этот dc(1) поставляется с поддержкой добавления сообщений об ошибках для разных локалей и, таким образом, поддерживает LC_MESSAGES.

SEE ALSO
       bc(1)

STANDARDS
       Операторы dc(1) и некоторые поведения соответствуют операторам спецификации IEEE Std 1003.1-2017 (“POSIX.1-2017”) bc(1) по адресу
       https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html .

BUGS
       Известных нет. Сообщайте об ошибках по адресу https://git.gavinhoward.com/gavin/bc .

AUTHOR
       Gavin D. Howard ⟨gavin@gavinhoward.com⟩ и участники.



Gavin D. Howard			  August 2024				 DC(1)
DC(1)			    General Commands Manual			 DC(1)



Name
       dc - arbitrary-precision decimal reverse-Polish notation calculator

SYNOPSIS
       dc [-cChiPRvVx] [--version] [--help] [--digit-clamp] [--no-digit-clamp]
       [--interactive] [--no-prompt] [--no-read-prompt] [--extended-register]
       [-e expr] [--expression=expr...]	 [-f file...]  [--file=file...]
       [file...]  [-I ibase] [--ibase=ibase] [-O obase] [--obase=obase] [-S
       scale] [--scale=scale] [-E seed] [--seed=seed]

DESCRIPTION
       dc(1) is an arbitrary-precision calculator.  It uses a stack (reverse
       Polish notation) to store numbers and results of computations.
       Arithmetic operations pop arguments off of the stack and push the
       results.

       If no files are given on the command-line, then dc(1) reads from stdin
       (see the STDIN section).	 Otherwise, those files are processed, and
       dc(1) will then exit.

       If a user wants to set up a standard environment, they can use
       DC_ENV_ARGS (see the ENVIRONMENT VARIABLES section).  For example, if a
       user wants the scale always set to 10, they can set DC_ENV_ARGS to -e
       10k, and this dc(1) will always start with a scale of 10.

OPTIONS
       The following are the options that dc(1) accepts.

       -C, --no-digit-clamp
	      Disables clamping of digits greater than or equal to the current
	      ibase when parsing numbers.

	      This means that the value added to a number from a digit is
	      always that digit’s value multiplied by the value of ibase
	      raised to the power of the digit’s position, which starts from 0
	      at the least significant digit.

	      If this and/or the -c or --digit-clamp options are given
	      multiple times, the last one given is used.

	      This option overrides the DC_DIGIT_CLAMP environment variable
	      (see the ENVIRONMENT VARIABLES section) and the default, which
	      can be queried with the -h or --help options.

	      This is a non-portable extension.

       -c, --digit-clamp
	      Enables clamping of digits greater than or equal to the current
	      ibase when parsing numbers.

	      This means that digits that the value added to a number from a
	      digit that is greater than or equal to the ibase is the value of
	      ibase minus 1 all multiplied by the value of ibase raised to the
	      power of the digit’s position, which starts from 0 at the least
	      significant digit.

	      If this and/or the -C or --no-digit-clamp options are given
	      multiple times, the last one given is used.

	      This option overrides the DC_DIGIT_CLAMP environment variable
	      (see the ENVIRONMENT VARIABLES section) and the default, which
	      can be queried with the -h or --help options.

	      This is a non-portable extension.

       -E seed, --seed=seed
	      Sets the builtin variable seed to the value seed assuming that
	      seed is in base 10.  It is a fatal error if seed is not a valid
	      number.

	      If multiple instances of this option are given, the last is
	      used.

	      This is a non-portable extension.

       -e expr, --expression=expr
	      Evaluates expr.  If multiple expressions are given, they are
	      evaluated in order.  If files are given as well (see below), the
	      expressions and files are evaluated in the order given.  This
	      means that if a file is given before an expression, the file is
	      read in and evaluated first.

	      If this option is given on the command-line (i.e., not in
	      DC_ENV_ARGS, see the ENVIRONMENT VARIABLES section), then after
	      processing all expressions and files, dc(1) will exit, unless -
	      (stdin) was given as an argument at least once to -f or --file,
	      whether on the command-line or in DC_ENV_ARGS.  However, if any
	      other -e, --expression, -f, or --file arguments are given after
	      -f- or equivalent is given, dc(1) will give a fatal error and
	      exit.

	      This is a non-portable extension.

       -f file, --file=file
	      Reads in file and evaluates it, line by line, as though it were
	      read through stdin.  If expressions are also given (see above),
	      the expressions are evaluated in the order given.

	      If this option is given on the command-line (i.e., not in
	      DC_ENV_ARGS, see the ENVIRONMENT VARIABLES section), then after
	      processing all expressions and files, dc(1) will exit, unless -
	      (stdin) was given as an argument at least once to -f or --file.
	      However, if any other -e, --expression, -f, or --file arguments
	      are given after -f- or equivalent is given, dc(1) will give a
	      fatal error and exit.

	      This is a non-portable extension.

       -h, --help
	      Prints a usage message and exits.

       -I ibase, --ibase=ibase
	      Sets the builtin variable ibase to the value ibase assuming that
	      ibase is in base 10.  It is a fatal error if ibase is not a
	      valid number.

	      If multiple instances of this option are given, the last is
	      used.

	      This is a non-portable extension.

       -i, --interactive
	      Forces interactive mode.	(See the INTERACTIVE MODE section.)

	      This is a non-portable extension.

       -L, --no-line-length
	      Disables line length checking and prints numbers without
	      backslashes and newlines.	 In other words, this option sets
	      BC_LINE_LENGTH to 0 (see the ENVIRONMENT VARIABLES section).

	      This is a non-portable extension.

       -O obase, --obase=obase
	      Sets the builtin variable obase to the value obase assuming that
	      obase is in base 10.  It is a fatal error if obase is not a
	      valid number.

	      If multiple instances of this option are given, the last is
	      used.

	      This is a non-portable extension.

       -P, --no-prompt
	      Disables the prompt in TTY mode.	(The prompt is only enabled in
	      TTY mode.	 See the TTY MODE section.)  This is mostly for those
	      users that do not want a prompt or are not used to having them
	      in dc(1).	 Most of those users would want to put this option in
	      DC_ENV_ARGS.

	      These options override the DC_PROMPT and DC_TTY_MODE environment
	      variables (see the ENVIRONMENT VARIABLES section).

	      This is a non-portable extension.

       -R, --no-read-prompt
	      Disables the read prompt in TTY mode.  (The read prompt is only
	      enabled in TTY mode.  See the TTY MODE section.)	This is mostly
	      for those users that do not want a read prompt or are not used
	      to having them in dc(1).	Most of those users would want to put
	      this option in BC_ENV_ARGS (see the ENVIRONMENT VARIABLES
	      section).	 This option is also useful in hash bang lines of
	      dc(1) scripts that prompt for user input.

	      This option does not disable the regular prompt because the read
	      prompt is only used when the ? command is used.

	      These options do override the DC_PROMPT and DC_TTY_MODE
	      environment variables (see the ENVIRONMENT VARIABLES section),
	      but only for the read prompt.

	      This is a non-portable extension.

       -S scale, --scale=scale
	      Sets the builtin variable scale to the value scale assuming that
	      scale is in base 10.  It is a fatal error if scale is not a
	      valid number.

	      If multiple instances of this option are given, the last is
	      used.

	      This is a non-portable extension.

       -v, -V, --version
	      Print the version information (copyright header) and exits.

       -x --extended-register
	      Enables extended register mode.  See the Extended Register Mode
	      subsection of the REGISTERS section for more information.

	      This is a non-portable extension.

       -z, --leading-zeroes
	      Makes dc(1) print all numbers greater than -1 and less than 1,
	      and not equal to 0, with a leading zero.

	      This is a non-portable extension.

       All long options are non-portable extensions.

STDIN
       If no files are given on the command-line and no files or expressions
       are given by the -f, --file, -e, or --expression options, then dc(1)
       reads from stdin.

       However, there is a caveat to this.

       First, stdin is evaluated a line at a time.  The only exception to this
       is if a string has been finished, but not ended.	 This means that,
       except for escaped brackets, all brackets must be balanced before dc(1)
       parses and executes.

STDOUT
       Any non-error output is written to stdout.  In addition, if history
       (see the HISTORY section) and the prompt (see the TTY MODE section) are
       enabled, both are output to stdout.

       Note: Unlike other dc(1) implementations, this dc(1) will issue a fatal
       error (see the EXIT STATUS section) if it cannot write to stdout, so if
       stdout is closed, as in dc  >&-, it will quit with an error.  This is
       done so that dc(1) can report problems when stdout is redirected to a
       file.

       If there are scripts that depend on the behavior of other dc(1)
       implementations, it is recommended that those scripts be changed to
       redirect stdout to /dev/null.

STDERR
       Any error output is written to stderr.

       Note: Unlike other dc(1) implementations, this dc(1) will issue a fatal
       error (see the EXIT STATUS section) if it cannot write to stderr, so if
       stderr is closed, as in dc  2>&-, it will quit with an error.  This is
       done so that dc(1) can exit with an error code when stderr is
       redirected to a file.

       If there are scripts that depend on the behavior of other dc(1)
       implementations, it is recommended that those scripts be changed to
       redirect stderr to /dev/null.

SYNTAX
       Each item in the input source code, either a number (see the NUMBERS
       section) or a command (see the COMMANDS section), is processed and
       executed, in order.  Input is processed immediately when entered.

       ibase is a register (see the REGISTERS section) that determines how to
       interpret constant numbers.  It is the “input” base, or the number base
       used for interpreting input numbers.  ibase is initially 10.  The max
       allowable value for ibase is 16.	 The min allowable value for ibase is
       2.  The max allowable value for ibase can be queried in dc(1) programs
       with the T command.

       obase is a register (see the REGISTERS section) that determines how to
       output results.	It is the “output” base, or the number base used for
       outputting numbers.  obase is initially 10.  The max allowable value
       for obase is DC_BASE_MAX and can be queried with the U command.	The
       min allowable value for obase is 0.  If obase is 0, values are output
       in scientific notation, and if obase is 1, values are output in
       engineering notation.  Otherwise, values are output in the specified
       base.

       Outputting in scientific and engineering notations are non-portable
       extensions.

       The scale of an expression is the number of digits in the result of the
       expression right of the decimal point, and scale is a register (see the
       REGISTERS section) that sets the precision of any operations (with
       exceptions).  scale is initially 0.  scale cannot be negative.  The max
       allowable value for scale can be queried in dc(1) programs with the V
       command.

       seed is a register containing the current seed for the pseudo-random
       number generator.  If the current value of seed is queried and stored,
       then if it is assigned to seed later, the pseudo-random number
       generator is guaranteed to produce the same sequence of pseudo-random
       numbers that were generated after the value of seed was first queried.

       Multiple values assigned to seed can produce the same sequence of
       pseudo-random numbers.  Likewise, when a value is assigned to seed, it
       is not guaranteed that querying seed immediately after will return the
       same value.  In addition, the value of seed will change after any call
       to the ’ command or the “ command that does not get receive a value of
       0 or 1.	The maximum integer returned by the ’ command can be queried
       with the W command.

       Note: The values returned by the pseudo-random number generator with
       the ’ and “ commands are guaranteed to NOT be cryptographically secure.
       This is a consequence of using a seeded pseudo-random number generator.
       However, they are guaranteed to be reproducible with identical seed
       values.	This means that the pseudo-random values from dc(1) should
       only be used where a reproducible stream of pseudo-random numbers is
       ESSENTIAL.  In any other case, use a non-seeded pseudo-random number
       generator.

       The pseudo-random number generator, seed, and all associated operations
       are non-portable extensions.

   Comments
       Comments go from # until, and not including, the next newline.  This is
       a non-portable extension.

NUMBERS
       Numbers are strings made up of digits, uppercase letters up to F, and
       at most 1 period for a radix.  Numbers can have up to DC_NUM_MAX
       digits.	Uppercase letters are equal to 9 plus their position in the
       alphabet (i.e., A equals 10, or 9+1).

       If a digit or letter makes no sense with the current value of ibase
       (i.e., they are greater than or equal to the current value of ibase),
       then the behavior depends on the existence of the -c/--digit-clamp or
       -C/--no-digit-clamp options (see the OPTIONS section), the existence
       and setting of the DC_DIGIT_CLAMP environment variable (see the
       ENVIRONMENT VARIABLES section), or the default, which can be queried
       with the -h/--help option.

       If clamping is off, then digits or letters that are greater than or
       equal to the current value of ibase are not changed.  Instead, their
       given value is multiplied by the appropriate power of ibase and added
       into the number.	 This means that, with an ibase of 3, the number AB is
       equal to 3^1*A+3^0*B, which is 3 times 10 plus 11, or 41.

       If clamping is on, then digits or letters that are greater than or
       equal to the current value of ibase are set to the value of the highest
       valid digit in ibase before being multiplied by the appropriate power
       of ibase and added into the number.  This means that, with an ibase of
       3, the number AB is equal to 3^1*2+3^0*2, which is 3 times 2 plus 2, or
       8.

       There is one exception to clamping: single-character numbers (i.e., A
       alone).	Such numbers are never clamped and always take the value they
       would have in the highest possible ibase.  This means that A alone
       always equals decimal 10 and Z alone always equals decimal 35.  This
       behavior is mandated by the standard for bc(1) (see the STANDARDS
       section) and is meant to provide an easy way to set the current ibase
       (with the i command) regardless of the current value of ibase.

       If clamping is on, and the clamped value of a character is needed, use
       a leading zero, i.e., for A, use 0A.

       In addition, dc(1) accepts numbers in scientific notation.  These have
       the form <number>e<integer>.  The exponent (the portion after the e)
       must be an integer.  An example is 1.89237e9, which is equal to
       1892370000.  Negative exponents are also allowed, so 4.2890e_3 is equal
       to 0.0042890.

       WARNING: Both the number and the exponent in scientific notation are
       interpreted according to the current ibase, but the number is still
       multiplied by 10^exponent regardless of the current ibase.  For
       example, if ibase is 16 and dc(1) is given the number string FFeA, the
       resulting decimal number will be 2550000000000, and if dc(1) is given
       the number string 10e_4, the resulting decimal number will be 0.0016.

       Accepting input as scientific notation is a non-portable extension.

COMMANDS
       The valid commands are listed below.

   Printing
       These commands are used for printing.

       Note that both scientific notation and engineering notation are
       available for printing numbers.	Scientific notation is activated by
       assigning 0 to obase using 0o, and engineering notation is activated by
       assigning 1 to obase using 1o.  To deactivate them, just assign a
       different value to obase.

       Printing numbers in scientific notation and/or engineering notation is
       a non-portable extension.

       p      Prints the value on top of the stack, whether number or string,
	      and prints a newline after.

	      This does not alter the stack.

       n      Prints the value on top of the stack, whether number or string,
	      and pops it off of the stack.

       P      Pops a value off the stack.

	      If the value is a number, it is truncated and the absolute value
	      of the result is printed as though obase is 256 and each digit
	      is interpreted as an 8-bit ASCII character, making it a byte
	      stream.

	      If the value is a string, it is printed without a trailing
	      newline.

	      This is a non-portable extension.

       f      Prints the entire contents of the stack, in order from newest to
	      oldest, without altering anything.

	      Users should use this command when they get lost.

   Arithmetic
       These are the commands used for arithmetic.

       +      The top two values are popped off the stack, added, and the
	      result is pushed onto the stack.	The scale of the result is
	      equal to the max scale of both operands.

       -      The top two values are popped off the stack, subtracted, and the
	      result is pushed onto the stack.	The scale of the result is
	      equal to the max scale of both operands.

       *      The top two values are popped off the stack, multiplied, and the
	      result is pushed onto the stack.	If a is the scale of the first
	      expression and b is the scale of the second expression, the
	      scale of the result is equal to min(a+b,max(scale,a,b)) where
	      min() and max() return the obvious values.

       /      The top two values are popped off the stack, divided, and the
	      result is pushed onto the stack.	The scale of the result is
	      equal to scale.

	      The first value popped off of the stack must be non-zero.

       %      The top two values are popped off the stack, remaindered, and
	      the result is pushed onto the stack.

	      Remaindering is equivalent to 1) Computing a/b to current scale,
	      and 2) Using the result of step 1 to calculate a-(a/b)*b to
	      scale max(scale+scale(b),scale(a)).

	      The first value popped off of the stack must be non-zero.

       ~      The top two values are popped off the stack, divided and
	      remaindered, and the results (divided first, remainder second)
	      are pushed onto the stack.  This is equivalent to x y / x y %
	      except that x and y are only evaluated once.

	      The first value popped off of the stack must be non-zero.

	      This is a non-portable extension.

       ^      The top two values are popped off the stack, the second is
	      raised to the power of the first, and the result is pushed onto
	      the stack.  The scale of the result is equal to scale.

	      The first value popped off of the stack must be an integer, and
	      if that value is negative, the second value popped off of the
	      stack must be non-zero.

       v      The top value is popped off the stack, its square root is
	      computed, and the result is pushed onto the stack.  The scale of
	      the result is equal to scale.

	      The value popped off of the stack must be non-negative.

       _      If this command immediately precedes a number (i.e., no spaces
	      or other commands), then that number is input as a negative
	      number.

	      Otherwise, the top value on the stack is popped and copied, and
	      the copy is negated and pushed onto the stack.  This behavior
	      without a number is a non-portable extension.

       b      The top value is popped off the stack, and if it is zero, it is
	      pushed back onto the stack.  Otherwise, its absolute value is
	      pushed onto the stack.

	      This is a non-portable extension.

       |      The top three values are popped off the stack, a modular
	      exponentiation is computed, and the result is pushed onto the
	      stack.

	      The first value popped is used as the reduction modulus and must
	      be an integer and non-zero.  The second value popped is used as
	      the exponent and must be an integer and non-negative.  The third
	      value popped is the base and must be an integer.

	      This is a non-portable extension.

       $      The top value is popped off the stack and copied, and the copy
	      is truncated and pushed onto the stack.

	      This is a non-portable extension.

       @      The top two values are popped off the stack, and the precision
	      of the second is set to the value of the first, whether by
	      truncation or extension.

	      The first value popped off of the stack must be an integer and
	      non-negative.

	      This is a non-portable extension.

       H      The top two values are popped off the stack, and the second is
	      shifted left (radix shifted right) to the value of the first.

	      The first value popped off of the stack must be an integer and
	      non-negative.

	      This is a non-portable extension.

       h      The top two values are popped off the stack, and the second is
	      shifted right (radix shifted left) to the value of the first.

	      The first value popped off of the stack must be an integer and
	      non-negative.

	      This is a non-portable extension.

       G      The top two values are popped off of the stack, they are
	      compared, and a 1 is pushed if they are equal, or 0 otherwise.

	      This is a non-portable extension.

       N      The top value is popped off of the stack, and if it a 0, a 1 is
	      pushed; otherwise, a 0 is pushed.

	      This is a non-portable extension.

       (      The top two values are popped off of the stack, they are
	      compared, and a 1 is pushed if the first is less than the
	      second, or 0 otherwise.

	      This is a non-portable extension.

       {      The top two values are popped off of the stack, they are
	      compared, and a 1 is pushed if the first is less than or equal
	      to the second, or 0 otherwise.

	      This is a non-portable extension.

       )      The top two values are popped off of the stack, they are
	      compared, and a 1 is pushed if the first is greater than the
	      second, or 0 otherwise.

	      This is a non-portable extension.

       }      The top two values are popped off of the stack, they are
	      compared, and a 1 is pushed if the first is greater than or
	      equal to the second, or 0 otherwise.

	      This is a non-portable extension.

       M      The top two values are popped off of the stack.  If they are
	      both non-zero, a 1 is pushed onto the stack.  If either of them
	      is zero, or both of them are, then a 0 is pushed onto the stack.

	      This is like the && operator in bc(1), and it is not a
	      short-circuit operator.

	      This is a non-portable extension.

       m      The top two values are popped off of the stack.  If at least one
	      of them is non-zero, a 1 is pushed onto the stack.  If both of
	      them are zero, then a 0 is pushed onto the stack.

	      This is like the || operator in bc(1), and it is not a
	      short-circuit operator.

	      This is a non-portable extension.

   Pseudo-Random Number Generator
       dc(1) has a built-in pseudo-random number generator.  These commands
       query the pseudo-random number generator.  (See Parameters for more
       information about the seed value that controls the pseudo-random number
       generator.)

       The pseudo-random number generator is guaranteed to NOT be
       cryptographically secure.

       ’      Generates an integer between 0 and DC_RAND_MAX, inclusive (see
	      the LIMITS section).

	      The generated integer is made as unbiased as possible, subject
	      to the limitations of the pseudo-random number generator.

	      This is a non-portable extension.

       “      Pops a value off of the stack, which is used as an exclusive
	      upper bound on the integer that will be generated.  If the bound
	      is negative or is a non-integer, an error is raised, and dc(1)
	      resets (see the RESET section) while seed remains unchanged.  If
	      the bound is larger than DC_RAND_MAX, the higher bound is
	      honored by generating several pseudo-random integers,
	      multiplying them by appropriate powers of DC_RAND_MAX+1, and
	      adding them together.  Thus, the size of integer that can be
	      generated with this command is unbounded.	 Using this command
	      will change the value of seed, unless the operand is 0 or 1.  In
	      that case, 0 is pushed onto the stack, and seed is not changed.

	      The generated integer is made as unbiased as possible, subject
	      to the limitations of the pseudo-random number generator.

	      This is a non-portable extension.

   Stack Control
       These commands control the stack.

       c      Removes all items from (“clears”) the stack.

       d      Copies the item on top of the stack (“duplicates”) and pushes
	      the copy onto the stack.

       r      Swaps (“reverses”) the two top items on the stack.

       R      Pops (“removes”) the top value from the stack.

   Register Control
       These commands control registers (see the REGISTERS section).

       sr     Pops the value off the top of the stack and stores it into
	      register r.

       lr     Copies the value in register r and pushes it onto the stack.
	      This does not alter the contents of r.

       Sr     Pops the value off the top of the (main) stack and pushes it
	      onto the stack of register r.  The previous value of the
	      register becomes inaccessible.

       Lr     Pops the value off the top of the stack for register r and push
	      it onto the main stack.  The previous value in the stack for
	      register r, if any, is now accessible via the lr command.

   Parameters
       These commands control the values of ibase, obase, scale, and seed.
       Also see the SYNTAX section.

       i      Pops the value off of the top of the stack and uses it to set
	      ibase, which must be between 2 and 16, inclusive.

	      If the value on top of the stack has any scale, the scale is
	      ignored.

       o      Pops the value off of the top of the stack and uses it to set
	      obase, which must be between 0 and DC_BASE_MAX, inclusive (see
	      the LIMITS section and the NUMBERS section).

	      If the value on top of the stack has any scale, the scale is
	      ignored.

       k      Pops the value off of the top of the stack and uses it to set
	      scale, which must be non-negative.

	      If the value on top of the stack has any scale, the scale is
	      ignored.

       j      Pops the value off of the top of the stack and uses it to set
	      seed.  The meaning of seed is dependent on the current
	      pseudo-random number generator but is guaranteed to not change
	      except for new major versions.

	      The scale and sign of the value may be significant.

	      If a previously used seed value is used again, the pseudo-random
	      number generator is guaranteed to produce the same sequence of
	      pseudo-random numbers as it did when the seed value was
	      previously used.

	      The exact value assigned to seed is not guaranteed to be
	      returned if the J command is used.  However, if seed does return
	      a different value, both values, when assigned to seed, are
	      guaranteed to produce the same sequence of pseudo-random
	      numbers.	This means that certain values assigned to seed will
	      not produce unique sequences of pseudo-random numbers.

	      There is no limit to the length (number of significant decimal
	      digits) or scale of the value that can be assigned to seed.

	      This is a non-portable extension.

       I      Pushes the current value of ibase onto the main stack.

       O      Pushes the current value of obase onto the main stack.

       K      Pushes the current value of scale onto the main stack.

       J      Pushes the current value of seed onto the main stack.

	      This is a non-portable extension.

       T      Pushes the maximum allowable value of ibase onto the main stack.

	      This is a non-portable extension.

       U      Pushes the maximum allowable value of obase onto the main stack.

	      This is a non-portable extension.

       V      Pushes the maximum allowable value of scale onto the main stack.

	      This is a non-portable extension.

       W      Pushes the maximum (inclusive) integer that can be generated
	      with the ’ pseudo-random number generator command.

	      This is a non-portable extension.

   Strings
       The following commands control strings.

       dc(1) can work with both numbers and strings, and registers (see the
       REGISTERS section) can hold both strings and numbers.  dc(1) always
       knows whether the contents of a register are a string or a number.

       While arithmetic operations have to have numbers, and will print an
       error if given a string, other commands accept strings.

       Strings can also be executed as macros.	For example, if the string
       [1pR] is executed as a macro, then the code 1pR is executed, meaning
       that the 1 will be printed with a newline after and then popped from
       the stack.

       [characters]
	      Makes a string containing characters and pushes it onto the
	      stack.

	      If there are brackets ([ and ]) in the string, then they must be
	      balanced.	 Unbalanced brackets can be escaped using a backslash
	      (\) character.

	      If there is a backslash character in the string, the character
	      after it (even another backslash) is put into the string
	      verbatim, but the (first) backslash is not.

       a      The value on top of the stack is popped.

	      If it is a number, it is truncated and its absolute value is
	      taken.  The result mod 256 is calculated.	 If that result is 0,
	      push an empty string; otherwise, push a one-character string
	      where the character is the result of the mod interpreted as an
	      ASCII character.

	      If it is a string, then a new string is made.  If the original
	      string is empty, the new string is empty.	 If it is not, then
	      the first character of the original string is used to create the
	      new string as a one-character string.  The new string is then
	      pushed onto the stack.

	      This is a non-portable extension.

       x      Pops a value off of the top of the stack.

	      If it is a number, it is pushed back onto the stack.

	      If it is a string, it is executed as a macro.

	      This behavior is the norm whenever a macro is executed, whether
	      by this command or by the conditional execution commands below.

       >r     Pops two values off of the stack that must be numbers and
	      compares them.  If the first value is greater than the second,
	      then the contents of register r are executed.

	      For example, 0 1>a will execute the contents of register a, and
	      1 0>a will not.

	      If either or both of the values are not numbers, dc(1) will
	      raise an error and reset (see the RESET section).

       >res   Like the above, but will execute register s if the comparison
	      fails.

	      If either or both of the values are not numbers, dc(1) will
	      raise an error and reset (see the RESET section).

	      This is a non-portable extension.

       !>r    Pops two values off of the stack that must be numbers and
	      compares them.  If the first value is not greater than the
	      second (less than or equal to), then the contents of register r
	      are executed.

	      If either or both of the values are not numbers, dc(1) will
	      raise an error and reset (see the RESET section).

       !>res  Like the above, but will execute register s if the comparison
	      fails.

	      If either or both of the values are not numbers, dc(1) will
	      raise an error and reset (see the RESET section).

	      This is a non-portable extension.

       <r     Pops two values off of the stack that must be numbers and
	      compares them.  If the first value is less than the second, then
	      the contents of register r are executed.

	      If either or both of the values are not numbers, dc(1) will
	      raise an error and reset (see the RESET section).

       <res   Like the above, but will execute register s if the comparison
	      fails.

	      If either or both of the values are not numbers, dc(1) will
	      raise an error and reset (see the RESET section).

	      This is a non-portable extension.

       !<r    Pops two values off of the stack that must be numbers and
	      compares them.  If the first value is not less than the second
	      (greater than or equal to), then the contents of register r are
	      executed.

	      If either or both of the values are not numbers, dc(1) will
	      raise an error and reset (see the RESET section).

       !<res  Like the above, but will execute register s if the comparison
	      fails.

	      If either or both of the values are not numbers, dc(1) will
	      raise an error and reset (see the RESET section).

	      This is a non-portable extension.

       =r     Pops two values off of the stack that must be numbers and
	      compares them.  If the first value is equal to the second, then
	      the contents of register r are executed.

	      If either or both of the values are not numbers, dc(1) will
	      raise an error and reset (see the RESET section).

       =res   Like the above, but will execute register s if the comparison
	      fails.

	      If either or both of the values are not numbers, dc(1) will
	      raise an error and reset (see the RESET section).

	      This is a non-portable extension.

       !=r    Pops two values off of the stack that must be numbers and
	      compares them.  If the first value is not equal to the second,
	      then the contents of register r are executed.

	      If either or both of the values are not numbers, dc(1) will
	      raise an error and reset (see the RESET section).

       !=res  Like the above, but will execute register s if the comparison
	      fails.

	      If either or both of the values are not numbers, dc(1) will
	      raise an error and reset (see the RESET section).

	      This is a non-portable extension.

       ?      Reads a line from the stdin and executes it.  This is to allow
	      macros to request input from users.

       q      During execution of a macro, this exits the execution of that
	      macro and the execution of the macro that executed it.  If there
	      are no macros, or only one macro executing, dc(1) exits.

       Q      Pops a value from the stack which must be non-negative and is
	      used the number of macro executions to pop off of the execution
	      stack.  If the number of levels to pop is greater than the
	      number of executing macros, dc(1) exits.

       ,      Pushes the depth of the execution stack onto the stack.  The
	      execution stack is the stack of string executions.  The number
	      that is pushed onto the stack is exactly as many as is needed to
	      make dc(1) exit with the Q command, so the sequence ,Q will make
	      dc(1) exit.

	      This is a non-portable extension.

   Status
       These commands query status of the stack or its top value.

       Z      Pops a value off of the stack.

	      If it is a number, calculates the number of significant decimal
	      digits it has and pushes the result.  It will push 1 if the
	      argument is 0 with no decimal places.

	      If it is a string, pushes the number of characters the string
	      has.

       X      Pops a value off of the stack.

	      If it is a number, pushes the scale of the value onto the stack.

	      If it is a string, pushes 0.

       u      Pops one value off of the stack.	If the value is a number, this
	      pushes 1 onto the stack.	Otherwise (if it is a string), it
	      pushes 0.

	      This is a non-portable extension.

       t      Pops one value off of the stack.	If the value is a string, this
	      pushes 1 onto the stack.	Otherwise (if it is a number), it
	      pushes 0.

	      This is a non-portable extension.

       z      Pushes the current depth of the stack (before execution of this
	      command) onto the stack.

       yr     Pushes the current stack depth of the register r onto the main
	      stack.

	      Because each register has a depth of 1 (with the value 0 in the
	      top item) when dc(1) starts, dc(1) requires that each register’s
	      stack must always have at least one item; dc(1) will give an
	      error and reset otherwise (see the RESET section).  This means
	      that this command will never push 0.

	      This is a non-portable extension.

   Arrays
       These commands manipulate arrays.

       :r     Pops the top two values off of the stack.	 The second value will
	      be stored in the array r (see the REGISTERS section), indexed by
	      the first value.

       ;r     Pops the value on top of the stack and uses it as an index into
	      the array r.  The selected value is then pushed onto the stack.

       Yr     Pushes the length of the array r onto the stack.

	      This is a non-portable extension.

   Global Settings
       These commands retrieve global settings.	 These are the only commands
       that require multiple specific characters, and all of them begin with
       the letter g.  Only the characters below are allowed after the
       character g; any other character produces a parse error (see the ERRORS
       section).

       gl     Pushes the line length set by DC_LINE_LENGTH (see the
	      ENVIRONMENT VARIABLES section) onto the stack.

       gx     Pushes 1 onto the stack if extended register mode is on, 0
	      otherwise.  See the Extended Register Mode subsection of the
	      REGISTERS section for more information.

       gz     Pushes 0 onto the stack if the leading zero setting has not been
	      enabled with the -z or --leading-zeroes options (see the OPTIONS
	      section), non-zero otherwise.

REGISTERS
       Registers are names that can store strings, numbers, and arrays.
       (Number/string registers do not interfere with array registers.)

       Each register is also its own stack, so the current register value is
       the top of the stack for the register.  All registers, when first
       referenced, have one value (0) in their stack, and it is a runtime
       error to attempt to pop that item off of the register stack.

       In non-extended register mode, a register name is just the single
       character that follows any command that needs a register name.  The
       only exceptions are: a newline (`\n') and a left bracket (`['); it is a
       parse error for a newline or a left bracket to be used as a register
       name.

   Extended Register Mode
       Unlike most other dc(1) implentations, this dc(1) provides nearly
       unlimited amounts of registers, if extended register mode is enabled.

       If extended register mode is enabled (-x or --extended-register
       command-line arguments are given), then normal single character
       registers are used unless the character immediately following a command
       that needs a register name is a space (according to isspace()) and not
       a newline (`\n').

       In that case, the register name is found according to the regex
       [a-z][a-z0-9_]* (like bc(1) identifiers), and it is a parse error if
       the next non-space characters do not match that regex.

RESET
       When dc(1) encounters an error or a signal that it has a non-default
       handler for, it resets.	This means that several things happen.

       First, any macros that are executing are stopped and popped off the
       execution stack.	 The behavior is not unlike that of exceptions in
       programming languages.  Then the execution point is set so that any
       code waiting to execute (after all macros returned) is skipped.

       However, the stack of values is not cleared; in interactive mode, users
       can inspect the stack and manipulate it.

       Thus, when dc(1) resets, it skips any remaining code waiting to be
       executed.  Then, if it is interactive mode, and the error was not a
       fatal error (see the EXIT STATUS section), it asks for more input;
       otherwise, it exits with the appropriate return code.

PERFORMANCE
       Most dc(1) implementations use char types to calculate the value of 1
       decimal digit at a time, but that can be slow.  This dc(1) does
       something different.

       It uses large integers to calculate more than 1 decimal digit at a
       time.  If built in a environment where DC_LONG_BIT (see the LIMITS
       section) is 64, then each integer has 9 decimal digits.	If built in an
       environment where DC_LONG_BIT is 32 then each integer has 4 decimal
       digits.	This value (the number of decimal digits per large integer) is
       called DC_BASE_DIGS.

       In addition, this dc(1) uses an even larger integer for overflow
       checking.  This integer type depends on the value of DC_LONG_BIT, but
       is always at least twice as large as the integer type used to store
       digits.

LIMITS
       The following are the limits on dc(1):

       DC_LONG_BIT
	      The number of bits in the long type in the environment where
	      dc(1) was built.	This determines how many decimal digits can be
	      stored in a single large integer (see the PERFORMANCE section).

       DC_BASE_DIGS
	      The number of decimal digits per large integer (see the
	      PERFORMANCE section).  Depends on DC_LONG_BIT.

       DC_BASE_POW
	      The max decimal number that each large integer can store (see
	      DC_BASE_DIGS) plus 1.  Depends on DC_BASE_DIGS.

       DC_OVERFLOW_MAX
	      The max number that the overflow type (see the PERFORMANCE
	      section) can hold.  Depends on DC_LONG_BIT.

       DC_BASE_MAX
	      The maximum output base.	Set at DC_BASE_POW.

       DC_DIM_MAX
	      The maximum size of arrays.  Set at SIZE_MAX-1.

       DC_SCALE_MAX
	      The maximum scale.  Set at DC_OVERFLOW_MAX-1.

       DC_STRING_MAX
	      The maximum length of strings.  Set at DC_OVERFLOW_MAX-1.

       DC_NAME_MAX
	      The maximum length of identifiers.  Set at DC_OVERFLOW_MAX-1.

       DC_NUM_MAX
	      The maximum length of a number (in decimal digits), which
	      includes digits after the decimal point.	Set at
	      DC_OVERFLOW_MAX-1.

       DC_RAND_MAX
	      The maximum integer (inclusive) returned by the ’ command, if
	      dc(1).  Set at 2^DC_LONG_BIT-1.

       Exponent
	      The maximum allowable exponent (positive or negative).  Set at
	      DC_OVERFLOW_MAX.

       Number of vars
	      The maximum number of vars/arrays.  Set at SIZE_MAX-1.

       These limits are meant to be effectively non-existent; the limits are
       so large (at least on 64-bit machines) that there should not be any
       point at which they become a problem.  In fact, memory should be
       exhausted before these limits should be hit.

ENVIRONMENT VARIABLES
       As non-portable extensions, dc(1) recognizes the following environment
       variables:

       DC_ENV_ARGS
	      This is another way to give command-line arguments to dc(1).
	      They should be in the same format as all other command-line
	      arguments.  These are always processed first, so any files given
	      in DC_ENV_ARGS will be processed before arguments and files
	      given on the command-line.  This gives the user the ability to
	      set up “standard” options and files to be used at every
	      invocation.  The most useful thing for such files to contain
	      would be useful functions that the user might want every time
	      dc(1) runs.  Another use would be to use the -e option to set
	      scale to a value other than 0.

	      The code that parses DC_ENV_ARGS will correctly handle quoted
	      arguments, but it does not understand escape sequences.  For
	      example, the string “/home/gavin/some dc file.dc” will be
	      correctly parsed, but the string “/home/gavin/some "dc" file.dc”
	      will include the backslashes.

	      The quote parsing will handle either kind of quotes, ’ or “.
	      Thus, if you have a file with any number of single quotes in the
	      name, you can use double quotes as the outside quotes, as in
	      “some `dc' file.dc”, and vice versa if you have a file with
	      double quotes.  However, handling a file with both kinds of
	      quotes in DC_ENV_ARGS is not supported due to the complexity of
	      the parsing, though such files are still supported on the
	      command-line where the parsing is done by the shell.

       DC_LINE_LENGTH
	      If this environment variable exists and contains an integer that
	      is greater than 1 and is less than UINT16_MAX (2^16-1), dc(1)
	      will output lines to that length, including the backslash
	      newline combo.  The default line length is 70.

	      The special value of 0 will disable line length checking and
	      print numbers without regard to line length and without
	      backslashes and newlines.

       DC_SIGINT_RESET
	      If dc(1) is not in interactive mode (see the INTERACTIVE MODE
	      section), then this environment variable has no effect because
	      dc(1) exits on SIGINT when not in interactive mode.

	      However, when dc(1) is in interactive mode, then if this
	      environment variable exists and contains an integer, a non-zero
	      value makes dc(1) reset on SIGINT, rather than exit, and zero
	      makes dc(1) exit.	 If this environment variable exists and is
	      not an integer, then dc(1) will exit on SIGINT.

	      This environment variable overrides the default, which can be
	      queried with the -h or --help options.

       DC_TTY_MODE
	      If TTY mode is not available (see the TTY MODE section), then
	      this environment variable has no effect.

	      However, when TTY mode is available, then if this environment
	      variable exists and contains an integer, then a non-zero value
	      makes dc(1) use TTY mode, and zero makes dc(1) not use TTY mode.

	      This environment variable overrides the default, which can be
	      queried with the -h or --help options.

       DC_PROMPT
	      If TTY mode is not available (see the TTY MODE section), then
	      this environment variable has no effect.

	      However, when TTY mode is available, then if this environment
	      variable exists and contains an integer, a non-zero value makes
	      dc(1) use a prompt, and zero or a non-integer makes dc(1) not
	      use a prompt.  If this environment variable does not exist and
	      DC_TTY_MODE does, then the value of the DC_TTY_MODE environment
	      variable is used.

	      This environment variable and the DC_TTY_MODE environment
	      variable override the default, which can be queried with the -h
	      or --help options.

       DC_EXPR_EXIT
	      If any expressions or expression files are given on the
	      command-line with -e, --expression, -f, or --file, then if this
	      environment variable exists and contains an integer, a non-zero
	      value makes dc(1) exit after executing the expressions and
	      expression files, and a zero value makes dc(1) not exit.

	      This environment variable overrides the default, which can be
	      queried with the -h or --help options.

       DC_DIGIT_CLAMP
	      When parsing numbers and if this environment variable exists and
	      contains an integer, a non-zero value makes dc(1) clamp digits
	      that are greater than or equal to the current ibase so that all
	      such digits are considered equal to the ibase minus 1, and a
	      zero value disables such clamping so that those digits are
	      always equal to their value, which is multiplied by the power of
	      the ibase.

	      This never applies to single-digit numbers, as per the bc(1)
	      standard (see the STANDARDS section).

	      This environment variable overrides the default, which can be
	      queried with the -h or --help options.

EXIT STATUS
       dc(1) returns the following exit statuses:

       0      No error.

       1      A math error occurred.  This follows standard practice of using
	      1 for expected errors, since math errors will happen in the
	      process of normal execution.

	      Math errors include divide by 0, taking the square root of a
	      negative number, using a negative number as a bound for the
	      pseudo-random number generator, attempting to convert a negative
	      number to a hardware integer, overflow when converting a number
	      to a hardware integer, overflow when calculating the size of a
	      number, and attempting to use a non-integer where an integer is
	      required.

	      Converting to a hardware integer happens for the second operand
	      of the power (^), places (@), left shift (H), and right shift
	      (h) operators.

       2      A parse error occurred.

	      Parse errors include unexpected EOF, using an invalid character,
	      failing to find the end of a string or comment, and using a
	      token where it is invalid.

       3      A runtime error occurred.

	      Runtime errors include assigning an invalid number to any global
	      (ibase, obase, or scale), giving a bad expression to a read()
	      call, calling read() inside of a read() call, type errors
	      (including attempting to execute a number), and attempting an
	      operation when the stack has too few elements.

       4      A fatal error occurred.

	      Fatal errors include memory allocation errors, I/O errors,
	      failing to open files, attempting to use files that do not have
	      only ASCII characters (dc(1) only accepts ASCII characters),
	      attempting to open a directory as a file, and giving invalid
	      command-line options.

       The exit status 4 is special; when a fatal error occurs, dc(1) always
       exits and returns 4, no matter what mode dc(1) is in.

       The other statuses will only be returned when dc(1) is not in
       interactive mode (see the INTERACTIVE MODE section), since dc(1) resets
       its state (see the RESET section) and accepts more input when one of
       those errors occurs in interactive mode.	 This is also the case when
       interactive mode is forced by the -i flag or --interactive option.

       These exit statuses allow dc(1) to be used in shell scripting with
       error checking, and its normal behavior can be forced by using the -i
       flag or --interactive option.

INTERACTIVE MODE
       Like bc(1), dc(1) has an interactive mode and a non-interactive mode.
       Interactive mode is turned on automatically when both stdin and stdout
       are hooked to a terminal, but the -i flag and --interactive option can
       turn it on in other situations.

       In interactive mode, dc(1) attempts to recover from errors (see the
       RESET section), and in normal execution, flushes stdout as soon as
       execution is done for the current input.	 dc(1) may also reset on
       SIGINT instead of exit, depending on the contents of, or default for,
       the DC_SIGINT_RESET environment variable (see the ENVIRONMENT VARIABLES
       section).

TTY MODE
       If stdin, stdout, and stderr are all connected to a TTY, then “TTY
       mode” is considered to be available, and thus, dc(1) can turn on TTY
       mode, subject to some settings.

       If there is the environment variable DC_TTY_MODE in the environment
       (see the ENVIRONMENT VARIABLES section), then if that environment
       variable contains a non-zero integer, dc(1) will turn on TTY mode when
       stdin, stdout, and stderr are all connected to a TTY.  If the
       DC_TTY_MODE environment variable exists but is not a non-zero integer,
       then dc(1) will not turn TTY mode on.

       If the environment variable DC_TTY_MODE does not exist, the default
       setting is used.	 The default setting can be queried with the -h or
       --help options.

       TTY mode is different from interactive mode because interactive mode is
       required in the bc(1) specification (see the STANDARDS section), and
       interactive mode requires only stdin and stdout to be connected to a
       terminal.

   Command-Line History
       Command-line history is only enabled if TTY mode is, i.e., that stdin,
       stdout, and stderr are connected to a TTY and the DC_TTY_MODE
       environment variable (see the ENVIRONMENT VARIABLES section) and its
       default do not disable TTY mode.	 See the COMMAND LINE HISTORY section
       for more information.

   Prompt
       If TTY mode is available, then a prompt can be enabled.	Like TTY mode
       itself, it can be turned on or off with an environment variable:
       DC_PROMPT (see the ENVIRONMENT VARIABLES section).

       If the environment variable DC_PROMPT exists and is a non-zero integer,
       then the prompt is turned on when stdin, stdout, and stderr are
       connected to a TTY and the -P and --no-prompt options were not used.
       The read prompt will be turned on under the same conditions, except
       that the -R and --no-read-prompt options must also not be used.

       However, if DC_PROMPT does not exist, the prompt can be enabled or
       disabled with the DC_TTY_MODE environment variable, the -P and
       --no-prompt options, and the -R and --no-read-prompt options.  See the
       ENVIRONMENT VARIABLES and OPTIONS sections for more details.

SIGNAL HANDLING
       Sending a SIGINT will cause dc(1) to do one of two things.

       If dc(1) is not in interactive mode (see the INTERACTIVE MODE section),
       or the DC_SIGINT_RESET environment variable (see the ENVIRONMENT
       VARIABLES section), or its default, is either not an integer or it is
       zero, dc(1) will exit.

       However, if dc(1) is in interactive mode, and the DC_SIGINT_RESET or
       its default is an integer and non-zero, then dc(1) will stop executing
       the current input and reset (see the RESET section) upon receiving a
       SIGINT.

       Note that “current input” can mean one of two things.  If dc(1) is
       processing input from stdin in interactive mode, it will ask for more
       input.  If dc(1) is processing input from a file in interactive mode,
       it will stop processing the file and start processing the next file, if
       one exists, or ask for input from stdin if no other file exists.

       This means that if a SIGINT is sent to dc(1) as it is executing a file,
       it can seem as though dc(1) did not respond to the signal since it will
       immediately start executing the next file.  This is by design; most
       files that users execute when interacting with dc(1) have function
       definitions, which are quick to parse.  If a file takes a long time to
       execute, there may be a bug in that file.  The rest of the files could
       still be executed without problem, allowing the user to continue.

       SIGTERM and SIGQUIT cause dc(1) to clean up and exit, and it uses the
       default handler for all other signals.  The one exception is SIGHUP; in
       that case, and only when dc(1) is in TTY mode (see the TTY MODE
       section), a SIGHUP will cause dc(1) to clean up and exit.

COMMAND LINE HISTORY
       dc(1) supports interactive command-line editing.

       If dc(1) can be in TTY mode (see the TTY MODE section), history can be
       enabled.	 This means that command-line history can only be enabled when
       stdin, stdout, and stderr are all connected to a TTY.

       Like TTY mode itself, it can be turned on or off with the environment
       variable DC_TTY_MODE (see the ENVIRONMENT VARIABLES section).

       Note: tabs are converted to 8 spaces.

LOCALES
       This dc(1) ships with support for adding error messages for different
       locales and thus, supports LC_MESSAGES.

SEE ALSO
       bc(1)

STANDARDS
       The dc(1) utility operators and some behavior are compliant with the
       operators in the IEEE Std 1003.1-2017 (“POSIX.1-2017”) bc(1)
       specification at
       https://pubs.opengroup.org/onlinepubs/9699919799/utilities/bc.html .

BUGS
       None are known.	Report bugs at https://git.gavinhoward.com/gavin/bc .

AUTHOR
       Gavin D. Howard ⟨gavin@gavinhoward.com⟩ and contributors.



Gavin D. Howard			  August 2024				 DC(1)

BC(1)			    Общие команды			BC(1)



NAME
       bc - язык арифметики с произвольной точностью и калькулятор

SYNOPSIS
       bc [-cCghilPqRsvVw] [--digit-clamp] [--no-digit-clamp]
       [--global-stacks] [--help] [--interactive] [--mathlib] [--no-prompt]
       [--no-read-prompt] [--quiet] [--standard] [--warn] [--version] [-e
       expr] [--expression=expr...]  [-f file...]  [--file=file...]  [file...]
       [-I ibase] [--ibase=ibase] [-O obase] [--obase=obase] [-S scale]
       [--scale=scale] [-E seed] [--seed=seed]

DESCRIPTION
       bc(1) является интерактивным процессором для языка, впервые стандартизированного в
       1991 году POSIX.  (См. раздел STANDARDS.)  Язык предоставляет
       арифметику с неограниченной точностью десятичных чисел и в некоторой степени похож на C, но
       есть различия.  Такие различия будут отмечены в этом
       документе.

       После разбора и обработки опций, этот bc(1) читает любые файлы, указанные в
       командной строке, и выполняет их перед чтением из stdin.

       Этот bc(1) является заменой для любого bc(1), включая (и
       особенно) GNU bc(1).  У него также есть множество расширений и дополнительных
       функций по сравнению с другими реализациями.

       Примечание: Если выполнение этого bc(1) на любом скрипте, предназначенном для другого bc(1), приводит к
       ошибке разбора, вероятно, это потому, что слово, которое этот bc(1) резервирует как
       ключевое слово, используется в качестве имени функции, переменной или массива.  Чтобы исправить
       это, используйте опцию командной строки -r keyword, где keyword -
       ключевое слово, которое используется как имя в скрипте.  Для получения дополнительной информации
       см. раздел OPTIONS.

       Если разбор скриптов, предназначенных для других реализаций bc(1), все равно не работает, это
       ошибка и должна быть сообщена.  См. раздел BUGS.

OPTIONS
       Следующие опции принимаются bc(1).

       -C, --no-digit-clamp
	      Отключает ограничение цифр, больших или равных текущему
	      ibase при разборе чисел.

	      Это означает, что значение, добавляемое к числу от цифры, всегда равно
	      значению этой цифры, умноженному на значение ibase,
	      возведенное в степень позиции цифры, которая начинается с 0
	      от наименее значимой цифры.

	      Если эта и/или опции -c или --digit-clamp даны
	      несколько раз, используется последняя из них.

	      Эта опция переопределяет переменную окружения BC_DIGIT_CLAMP (см. раздел ENVIRONMENT VARIABLES)
	      и значение по умолчанию, которое можно запросить с опциями -h или --help.

	      Это нестандартное расширение.

       -c, --digit-clamp
	      Включает ограничение цифр, больших или равных текущему
	      ibase при разборе чисел.

	      Это означает, что значение, добавляемое к числу от цифры, которая больше или равна
	      ibase, равно значению ibase минус 1, умноженному на значение ibase,
	      возведенное в степень позиции цифры, которая начинается с 0
	      от наименее значимой цифры.

	      Если эта и/или опции -C или --no-digit-clamp даны
	      несколько раз, используется последняя из них.

	      Эта опция переопределяет переменную окружения BC_DIGIT_CLAMP (см. раздел ENVIRONMENT VARIABLES)
	      и значение по умолчанию, которое можно запросить с опциями -h или --help.

	      Это нестандартное расширение.

       -E seed, --seed=seed
	      Устанавливает встроенную переменную seed на значение seed, предполагая, что
	      seed в базе 10.  Это фатальная ошибка, если seed не является
	      допустимым числом.

	      Если несколько экземпляров этой опции даны, используется последняя.

	      Это нестандартное расширение.

       -e expr, --expression=expr
	      Вычисляет expr.  Если несколько выражений даны, они
	      вычисляются в порядке.  Если файлы также даны (см. опции -f и
	      --file), выражения и файлы вычисляются в порядке, в котором они даны.  Это означает, что если файл дан до
	      выражения, файл читается и вычисляется первым.

	      Если эта опция дана в командной строке (т.е. не в
	      BC_ENV_ARGS, см. раздел ENVIRONMENT VARIABLES), то после
	      обработки всех выражений и файлов, bc(1) выйдет, если не был
	      дан - (stdin) в качестве аргумента хотя бы раз для -f или --file,
	      независимо от того, в командной строке или в BC_ENV_ARGS.  Однако, если любые другие -e, --expression, -f или --file аргументы даны после
	      -f- или эквивалентного, bc(1) выдаст фатальную ошибку и
	      выйдет.

	      Это нестандартное расширение.

       -f file, --file=file
	      Читает file и вычисляет его построчно, как будто он был
	      прочитан через stdin.  Если выражения также даны (см. опции -e
	      и --expression), выражения вычисляются в порядке, в котором они даны.

	      Если эта опция дана в командной строке (т.е. не в
	      BC_ENV_ARGS, см. раздел ENVIRONMENT VARIABLES), то после
	      обработки всех выражений и файлов, bc(1) выйдет, если не был
	      дан - (stdin) в качестве аргумента хотя бы раз для -f или --file.
	      Однако, если любые другие -e, --expression, -f или --file аргументы даны после
	      -f- или эквивалентного, bc(1) выдаст фатальную ошибку и
	      выйдет.

	      Это нестандартное расширение.

       -g, --global-stacks
	      Превращает глобальные переменные ibase, obase, scale и seed в стеки.

	      Это означает, что копия текущего значения всех четырех
	      помещается в стек при каждом вызове функции, а также
	      извлекается, когда каждая функция возвращается.  Это означает, что функции
	      могут присваивать значения любым и всем этим глобальным переменным без опасений, что
	      изменение повлияет на другие функции.  Таким образом, гипотетическая
	      функция named output(x,b), которая просто печатает x в базе b, может
	      быть написана так:

		     define void output(x, b) {
			 obase=b
			 x
		     }

	      вместо так:

		     define void output(x, b) {
			 auto c
			 c=obase
			 obase=b
			 x
			 obase=c
		     }

	      Это упрощает написание функций.

	      (Примечание: функция output(x,b) существует в расширенной математической
	      библиотеке.  См. раздел LIBRARY.)

	      Однако, поскольку использование этой опции означает, что функции не могут установить
	      ibase, obase, scale или seed глобально, функции, предназначенные для этого, больше не могут работать.  Существуют два возможных случая использования для этого, и каждый имеет решение.

	      Во-первых, если функция вызывается при запуске для превращения bc(1) в
	      преобразователь чисел, возможно заменить эту возможность
	      различными псевдонимами оболочки.  Примеры:

		     alias d2o="bc -e ibase=A -e obase=8"
		     alias h2b="bc -e ibase=G -e obase=2"

	      Во-вторых, если цель функции - установить ibase, obase,
	      scale или seed глобально для любой другой цели, она может быть разделена
	      на одну-четыре функции (на основе того, сколько глобальных переменных она устанавливает)
	      и каждая из этих функций может возвращать желаемое значение для
	      глобальной переменной.

	      Для функций, которые устанавливают seed, значение, присвоенное seed, не
	      распространяется на родительские функции.  Это означает, что последовательность
	      псевдослучайных чисел, которую они видят, не будет той же последовательностью псевдослучайных чисел, которую видят
	      любые родители.  Это верно только после того, как seed был установлен.

	      Если функция желает не повлиять на последовательность псевдослучайных чисел
	      своих родителей, но хочет использовать тот же seed, она
	      может использовать следующую строку:

		     seed = seed

	      Если поведение этой опции желательно для каждого запуска
	      bc(1), пользователи могут убедиться, что определена BC_ENV_ARGS и в ней
	      включена эта опция (см. раздел ENVIRONMENT VARIABLES для
	      получения дополнительной информации).

	      Если используются -s, -w или любые эквиваленты, эта опция игнорируется.

	      Это нестандартное расширение.

       -h, --help
	      Печатает сообщение использования и выходит.

       -I ibase, --ibase=ibase
	      Устанавливает встроенную переменную ibase на значение ibase, предполагая, что
	      ibase в базе 10.  Это фатальная ошибка, если ibase не является
	      допустимым числом.

	      Если несколько экземпляров этой опции даны, используется последняя.

	      Это нестандартное расширение.

       -i, --interactive
	      Принудительно включает интерактивный режим.  (См. раздел INTERACTIVE MODE.)

	      Это нестандартное расширение.

       -L, --no-line-length
	      Отключает проверку длины строки и печатает числа без обратных
	      слэшей и новой строки.  Иными словами, эта опция устанавливает
	      BC_LINE_LENGTH на 0 (см. раздел ENVIRONMENT VARIABLES).

	      Это нестандартное расширение.

       -l, --mathlib
	      Устанавливает scale (см. раздел SYNTAX) на 20 и загружает встроенную
	      математическую библиотеку и расширенную математическую библиотеку перед запуском любого
	      кода, включая любые выражения или файлы, указанные в
	      командной строке.

	      Чтобы узнать, что в библиотеках, см. раздел LIBRARY.

       -O obase, --obase=obase
	      Устанавливает встроенную переменную obase на значение obase, предполагая, что
	      obase в базе 10.  Это фатальная ошибка, если obase не является
	      допустимым числом.

	      Если несколько экземпляров этой опции даны, используется последняя.

	      Это нестандартное расширение.

       -P, --no-prompt
	      Отключает подсказку в режиме TTY.  (Подсказка включается только в
	      режиме TTY.  См. раздел TTY MODE.)  Это в основном для тех
	      пользователей, которые не хотят подсказки или не привыкли к ним в bc(1).
	      Большинство таких пользователей захотят добавить эту опцию в
	      BC_ENV_ARGS (см. раздел ENVIRONMENT VARIABLES).

	      Эти опции переопределяют переменные окружения BC_PROMPT и BC_TTY_MODE (см. раздел ENVIRONMENT VARIABLES).

	      Это нестандартное расширение.

       -q, --quiet
	      Эта опция для совместимости с GNU bc(1)
	      (https://www.gnu.org/software/bc/); она не делает ничего.  Без этой
	      опции, GNU bc(1) печатает заголовок с авторскими правами.  Этот bc(1) печатает
	      заголовок с авторскими правами только если одна или несколько из опций -v, -V или
	      --version даны, если переменная окружения BC_BANNER установлена и содержит
	      ненулевое целое число или если этот bc(1) был построен с заголовком по умолчанию.  Если это так,
	      то эта опция предотвращает печать заголовка bc(1).

	      Это нестандартное расширение.

       -R, --no-read-prompt
	      Отключает подсказку чтения в режиме TTY.  (Подсказка чтения включается только в
	      режиме TTY.  См. раздел TTY MODE.)  Это в основном для тех
	      пользователей, которые не хотят подсказки чтения или не привыкли к ним в bc(1).
	      Большинство таких пользователей захотят добавить эту опцию в
	      BC_ENV_ARGS (см. раздел ENVIRONMENT VARIABLES).  Эта опция также полезна в строках
	      hash bang скриптов bc(1), которые запрашивают ввод от пользователя.

	      Эта опция не отключает обычную подсказку, потому что подсказка чтения используется только когда вызывается встроенная функция read().

	      Эти опции переопределяют переменные окружения BC_PROMPT и BC_TTY_MODE (см. раздел ENVIRONMENT VARIABLES), но только
	      для подсказки чтения.

	      Это нестандартное расширение.

       -r keyword, --redefine=keyword
	      Переопределяет keyword, чтобы позволить его использовать как функцию,
	      переменную или имя массива.  Это полезно, когда этот bc(1) выдает
	      ошибки разбора при разборе скриптов, предназначенных для других реализаций bc(1).

	      Ключевые слова, которые этот bc(1) позволяет переопределять, следующие:

	      • abs

	      • asciify

	      • continue

	      • divmod

	      • else

	      • halt

	      • irand

	      • last

	      • limits

	      • maxibase

	      • maxobase

	      • maxrand

	      • maxscale

	      • modexp

	      • print

	      • rand

	      • read

	      • seed

	      • stream

	      Если любое из этих ключевых слов используется как функция, переменная или
	      имя массива в скрипте, используйте эту опцию с ключевым словом в качестве
	      аргумента.  Если несколько используются, используйте эту опцию для всех из
	      них; она может быть использована несколько раз.

	      Ключевые слова не переопределяются при разборе встроенной математической библиотеки
	      (см. раздел LIBRARY).

	      Это фатальная ошибка переопределять ключевые слова, предписанные стандартом POSIX
	      (см. раздел STANDARDS).  Это фатальная ошибка попытаться
	      переопределить слова, которые этот bc(1) не резервирует как
	      ключевые слова.

       -S scale, --scale=scale
	      Устанавливает встроенную переменную scale на значение scale, предполагая, что
	      scale в базе 10.  Это фатальная ошибка, если scale не является
	      допустимым числом.

	      Если несколько экземпляров этой опции даны, используется последняя.

	      Это нестандартное расширение.

       -s, --standard
	      Обрабатывает ровно язык, определенный стандартом (см. раздел
	      STANDARDS), и выдает ошибку, если используются любые расширения.

	      Это нестандартное расширение.

       -v, -V, --version
	      Печатает информацию о версии (заголовок с авторскими правами) и выходит.

	      Это нестандартное расширение.

       -w, --warn
	      Как -s и --standard, кроме того, что предупреждения (а не ошибки)
	      печатаются для нестандартных расширений и выполнение продолжается
	      нормально.

	      Это нестандартное расширение.

       -z, --leading-zeroes
	      Делает bc(1) печатать все числа больше -1 и меньше 1,
	      и не равные 0, с ведущим нулем.

	      Это можно установить для отдельных чисел с функциями plz(x),
	      plznl(x), pnlz(x) и pnlznl(x) в расширенной математической
	      библиотеке (см. раздел LIBRARY).

	      Это нестандартное расширение.

       Все длинные опции являются нестандартными расширениями.

STDIN
       Если файлы или выражения не даны опциями -f, --file, -e или --ex‐
       pression, то bc(1) читает из stdin.

       Однако, есть несколько нюансов.

       Во-первых, stdin оценивается построчно.  Единственное исключение - если разбор не может
       завершиться.  Это означает, что начало строки без конца или начало функции, оператора if или цикла без
       конца приведет к тому, что bc(1) не выполнит.

       Во-вторых, после оператора if, bc(1) не знает, последует ли оператор else, так что он
       не выполнит, пока не узнает, что оператора else не будет.

STDOUT
       Любая ненулевая выходная информация пишется в stdout.  Кроме того, если история
       (см. раздел HISTORY) и подсказка (см. раздел TTY MODE) включены, оба выводятся в stdout.

       Примечание: В отличие от других реализаций bc(1), этот bc(1) выдаст фатальную
       ошибку (см. раздел EXIT STATUS), если не сможет писать в stdout, так что если stdout закрыт, как в bc  >&-, он выйдет с ошибкой.  Это сделано, чтобы bc(1) мог сообщать о проблемах, когда stdout перенаправлен в
       файл.

       Если есть скрипты, которые зависят от поведения других реализаций bc(1), рекомендуется изменить эти скрипты, чтобы перенаправлять
       stdout в /dev/null.

STDERR
       Любая выходная информация об ошибках пишется в stderr.

       Примечание: В отличие от других реализаций bc(1), этот bc(1) выдаст фатальную
       ошибку (см. раздел EXIT STATUS), если не сможет писать в stderr, так что если stderr закрыт, как в bc  2>&-, он выйдет с ошибкой.  Это сделано, чтобы bc(1) мог выйти с кодом ошибки, когда stderr перенаправлен в
       файл.

       Если есть скрипты, которые зависят от поведения других реализаций bc(1), рекомендуется изменить эти скрипты, чтобы перенаправлять
       stderr в /dev/null.

SYNTAX
       Синтаксис программ bc(1) в основном похож на C, с некоторыми различиями.
       Этот bc(1) следует стандарту POSIX (см. раздел STANDARDS),
       который является более thorough ресурсом для языка, который принимает этот bc(1).  Этот раздел предназначен для того, чтобы быть кратким обзором и списком всех
       расширений к стандарту.

       В разделах ниже E означает выражение, S означает оператор, а I
       означает идентификатор.

       Идентификаторы (I) начинаются с маленькой буквы и могут быть followed любым числом (до BC_NAME_MAX-1) маленьких букв (a-z), цифр
       (0-9) и подчеркиваний (_).  Регулярное выражение - [a-z][a-z0-9_]*.  Идентификаторы
       с более чем одним символом (буквой) являются нестандартным расширением.

       ibase является глобальной переменной, определяющей, как интерпретировать константные числа.  Это "input" база, или числовая база, используемая для интерпретации
       входных чисел.  ibase изначально 10.  Если флаги -s (--standard) и -w
       (--warn) не даны в командной строке, максимальное допустимое значение для ibase - 36.  В противном случае, оно - 16.  Минимальное допустимое значение
       для ibase - 2.  Максимальное допустимое значение для ibase можно запросить в
       программах bc(1) с встроенной функцией maxibase().

       obase является глобальной переменной, определяющей, как выводить результаты.  Это
       "output" база, или числовая база, используемая для вывода чисел.
       obase изначально 10.  Максимальное допустимое значение для obase -
       BC_BASE_MAX и может быть запрошено в программах bc(1) с функцией maxobase().
       Минимальное допустимое значение для obase - 0.  Если obase
       равно 0, значения выводятся в научной нотации, а если obase равно 1, значения выводятся в
       инженерной нотации.  В противном случае, значения выводятся в указанной базе.

       Вывод в научной и инженерной нотациях являются нестандартными расширениями.

       Масштаб выражения - это количество цифр в результате выражения справа от десятичной точки, и scale является глобальной переменной,
       которая устанавливает точность любых операций, с исключениями.  scale изначально 0.  scale не может быть отрицательным.  Максимальное допустимое значение для
       scale - BC_SCALE_MAX и может быть запрошено в программах bc(1) с функцией
       maxscale().

       bc(1) имеет как глобальные переменные, так и локальные переменные.  Все локальные переменные локальны для функции; они являются параметрами или введены
       в списке auto функции (см. раздел FUNCTIONS).  Если доступна переменная, которая не является параметром или в списке auto, предполагается, что она глобальная.  Если родительская функция имеет локальную версию переменной, которую дочерняя функция считает глобальной, значение этой глобальной переменной в дочерней функции - значение переменной
       в родительской функции, а не значение фактической глобальной переменной.

       Все вышеперечисленное применяется и к массивам.

       Значение оператора, который является выражением (т.е. любое из именованных выражений или операндов), печатается, если оператор наименьшей приоритетности -
       оператор присваивания и выражение не окружено
       скобками.

       Значение, которое печатается, также присваивается специальной переменной
       last.  Одиночная точка (.) может также использоваться как синоним для last.  Это нестандартное расширение.

       Либо точки с запятой, либо новые строки могут разделять операторы.

   Comments
       Существуют два вида комментариев:

       1. Блочные комментарии заключены в /* и */.

       2. Строковые комментарии идут от # до, и не включая, следующей новой строки.
	  Это нестандартное расширение.

   Named Expressions
       Следующие являются именованными выражениями в bc(1):

       1. Переменные: I

       2. Элементы массива: I[E]

       3. ibase

       4. obase

       5. scale

       6. seed

       7. last или одиночная точка (.)

       Пункты 6 и 7 являются нестандартными расширениями.

       Значение seed зависит от текущего генератора псевдослучайных чисел, но гарантируется, что оно не изменится, кроме как для новых основных версий.

       Масштаб и знак значения могут быть значимыми.

       Если ранее использованное значение seed присвоено seed и использовано снова, генератор
       псевдослучайных чисел гарантируется производить ту же последовательность псевдослучайных чисел, что и при предыдущем использовании значения seed.

       Точное значение, присвоенное seed, не гарантируется быть возвращенным, если seed запрошен снова немедленно.  Однако, если seed возвращает другое значение, оба значения, когда присвоены seed, гарантируются производить ту же последовательность псевдослучайных чисел.  Это означает, что некоторые значения, присвоенные seed, не будут производить уникальные последовательности псевдослучайных чисел.  Значение seed изменится после любого использования
       операндов rand() и irand(E) (см. подраздел Operands ниже),
       кроме если параметр, переданный irand(E), равен 0, 1 или отрицательному.

       Нет ограничения на длину (количество значимых десятичных цифр)
       или масштаб значения, которое может быть присвоено seed.

       Переменные и массивы не мешают; пользователи могут иметь массивы с именами, такими же, как у переменных.  Это также применяется к функциям (см. раздел FUNCTIONS), так что пользователь может иметь переменную, массив и функцию, которые все
       имеют одно и то же имя, и они не будут затенять друг друга, независимо от того, внутри функций или нет.

       Именованные выражения требуются в качестве операнда операторов инкремента/декремента и как левая сторона операторов присваивания (см. подраздел
       Operators).

   Operands
       Следующие являются допустимыми операндами в bc(1):

	1. Числа (см. подраздел Numbers ниже).

	2. Индексы массива (I[E]).

	3. (E): Значение E (используется для изменения приоритета).

	4. sqrt(E): Квадратный корень из E.  E должно быть неотрицательным.

	5. length(E): Количество значимых десятичных цифр в E.  Возвращает
	   1 для 0 без десятичных знаков.  Если дано строку, возвращается длина
	   строки.  Передача строки length(E) является
	   нестандартным расширением.

	6. length(I[]): Количество элементов в массиве I.  Это нестандартное
	   расширение.

	7. scale(E): Масштаб E.

	8. abs(E): Абсолютное значение E.  Это нестандартное расширение.

	9. is_number(E): 1, если данный аргумент является числом, 0, если это строка.  Это нестандартное расширение.

       10. is_string(E): 1, если данный аргумент является строкой, 0, если это число.  Это нестандартное расширение.

       11. modexp(E, E, E): Модульное возведение в степень, где первое выражение
	   - база, второе - показатель степени, а третье - модуль.  Все три значения должны быть целыми.  Второе аргумент должен быть неотрицательным.  Третье аргумент должно быть ненулевым.  Это нестандартное расширение.

       12. divmod(E, E, I[]): Деление и модуль в одной операции.  Это для
	   оптимизации.  Первое выражение - делимое, а второе - делитель, который должен быть ненулевым.  Возвращаемое значение - частное, а модуль хранится в индексе 0 предоставленного
	   массива (последний аргумент).  Это нестандартное расширение.

       13. asciify(E): Если E является строкой, возвращает строку, которая является первым
	   символом ее аргумента.  Если это число, вычисляет число
	   mod 256 и возвращает это число как строку из одного символа.  Это нестандартное расширение.

       14. asciify(I[]): Строка, которая состоит из символов, которые бы
	   resulted от выполнения asciify(E) на каждом элементе массива,
	   идентифицируемого аргументом.  Это позволяет создавать многосимвольные строки
	   и хранить их.  Это нестандартное расширение.

       15. I(), I(E), I(E, E) и так далее, где I является идентификатором для
	   не-void функции (см. подраздел Void Functions раздела FUNC‐
	   TIONS).  Аргумент(ы) E также может быть массивами в форме
	   I[], которые автоматически преобразуются в ссылки на массивы (см.
	   подраздел Array References раздела FUNCTIONS), если соответствующий параметр в определении функции - ссылка на массив.

       16. read(): Читает строку из stdin и использует ее как выражение.
	   Результат этого выражения - результат операнда read().  Это нестандартное расширение.

       17. maxibase(): Максимальное допустимое ibase.  Это нестандартное расширение.

       18. maxobase(): Максимальное допустимое obase.  Это нестандартное расширение.

       19. maxscale(): Максимальное допустимое scale.  Это нестандартное расширение.

       20. line_length(): Длина строки, установленная с BC_LINE_LENGTH (см. раздел EN‐
	   VIRONMENT VARIABLES).  Это нестандартное расширение.

       21. global_stacks(): 0, если глобальные стеки не включены с опциями -g или
	   --global-stacks, иначе ненулевое.  См. раздел OPTIONS.  Это нестандартное расширение.

       22. leading_zero(): 0, если ведущие нули не включены с опциями -z или
	   –leading-zeroes, иначе ненулевое.  См. раздел OPTIONS.  Это нестандартное расширение.

       23. rand(): Псевдослучайное целое число между 0 (включительно) и
	   BC_RAND_MAX (включительно).  Использование этого операнда изменит значение
	   seed.  Это нестандартное расширение.

       24. irand(E): Псевдослучайное целое число между 0 (включительно) и значением E (исключительно).  Если E отрицательное или не целое (масштаб E не 0), возникает ошибка, и bc(1) сбрасывается (см. раздел RE‐
	   SET), в то время как seed остается неизменным.  Если E больше
	   BC_RAND_MAX, верхний предел соблюдается, генерируя несколько
	   псевдослучайных целых чисел, умножая их на подходящие степени BC_RAND_MAX+1 и добавляя их вместе.  Таким образом, размер целого числа,
	   которое может быть сгенерировано с этим операндом, неограничен.  Использование этого
	   операнда изменит значение seed, если значение E не 0
	   или 1.  В этом случае возвращается 0, и seed не изменяется.  Это
	   нестандартное расширение.

       25. maxrand(): Максимальное целое число, возвращаемое rand().  Это нестандартное расширение.

       Целые числа, генерируемые rand() и irand(E), гарантируются быть такими же беспристрастными, насколько возможно, с учетом ограничений генератора псевдослучайных чисел.

       Примечание: Значения, возвращаемые генератором псевдослучайных чисел с
       rand() и irand(E), гарантируются НЕ быть криптографически безопасными.
       Это следствие использования засеянного генератора псевдослучайных чисел.
       Однако, они гарантируются быть воспроизводимыми с идентичными значениями seed.
       Это означает, что псевдослучайные значения от bc(1) должны использоваться только там, где поток псевдослучайных чисел, воспроизводимый, является
       КРИТИЧЕСКИ важным.  В любом другом случае используйте несеянный генератор псевдослучайных чисел.

   Numbers
       Числа являются строками, состоящими из цифр, прописных букв и не более 1
       точки для radix.  Числа могут иметь до BC_NUM_MAX цифр.  Прописные буквы равны 9 плюс их позиция в алфавите,
       начиная с 1 (т.е. A равно 10, или 9+1).

       Если цифра или буква не имеет смысла с текущим значением ibase
       (т.е. они больше или равны текущему значению ibase),
       то поведение зависит от наличия опций -c/--digit-clamp или
       -C/--no-digit-clamp (см. раздел OPTIONS), наличия и настройки переменной окружения BC_DIGIT_CLAMP (см. раздел ENVI‐
       RONMENT VARIABLES) или значения по умолчанию, которое можно запросить с опциями -h/--help.

       Если ограничение выключено, то цифры или буквы, которые больше или
       равны текущему значению ibase, не изменяются.  Вместо этого, их
       данное значение умножается на подходящую степень ibase и добавляется
       в число.  Это означает, что с ibase 3, число AB равно
       3^1*A+3^0*B, что равно 3 раза 10 плюс 11, или 41.

       Если ограничение включено, то цифры или буквы, которые больше или
       равны текущему значению ibase, устанавливаются на значение самой высокой
       допустимой цифры в ibase перед умножением на подходящую степень
       ibase и добавлением в число.  Это означает, что с ibase 3, число AB равно
       3^1*2+3^0*2, что равно 3 раза 2 плюс 2, или 8.

       Существует одно исключение из ограничения: однозначные числа (т.е. A
       в одиночку).  Такие числа никогда не ограничиваются и всегда принимают значение, которое они
       бы имели в самой высокой возможной ibase.  Это означает, что A в одиночку
       всегда равно десятичному 10, а Z в одиночку всегда равно десятичному 35.  Это поведение предписано стандартом (см. раздел STANDARDS) и предназначено для предоставления простого способа установки текущего ibase (с командой i) независимо от текущего значения ibase.

       Если ограничение включено и значение ограниченной цифры needed, используйте ведущий нуль, т.е. для A используйте 0A.

       Кроме того, bc(1) принимает числа в научной нотации.  Эти имеют
       форму <number>e<integer>.  Показатель (часть после e)
       должен быть целым.  Пример - 1.89237e9, что равно
       1892370000.  Отрицательные показатели также разрешены, так что 4.2890e-3 равно 0.0042890.

       Использование научной нотации является ошибкой или предупреждением, если опции -s или -w соответственно даны в командной строке (или эквиваленты).

       ПРЕДУПРЕЖДЕНИЕ: Как число, так и показатель в научной нотации интерпретируются в соответствии с текущим ibase, но число все равно умножается на 10^exponent независимо от текущего ibase.  Например, если ibase равно 16 и bc(1) дано строковое число FFeA, результирующее десятичное число будет 2550000000000, а если bc(1) дано строковое число 10e-4, результирующее десятичное число будет 0.0016.

       Принятие ввода в научной нотации является нестандартным расширением.

   Operators
       Следующие арифметические и логические операторы могут быть использованы.  Они перечислены в порядке убывания приоритета.  Операторы в одной группе
       имеют одинаковый приоритет.

       ++ --  Тип: Префиксный и постфиксный

	      Ассоциативность: Нет

	      Описание: инкремент, декремент

       - !    Тип: Префиксный

	      Ассоциативность: Нет

	      Описание: отрицание, логическое не

       $      Тип: Постфиксный

	      Ассоциативность: Нет

	      Описание: усечение

       @      Тип: Бинарный

	      Ассоциативность: Справа

	      Описание: установка точности

       ^      Тип: Бинарный

	      Ассоциативность: Справа

	      Описание: возведение в степень

       * / %  Тип: Бинарный

	      Ассоциативность: Слева

	      Описание: умножение, деление, модуль

       + -    Тип: Бинарный

	      Ассоциативность: Слева

	      Описание: сложение, вычитание

       << >>  Тип: Бинарный

	      Ассоциативность: Слева

	      Описание: сдвиг влево, сдвиг вправо

       = <<= >>= += -= *= /= %= ^= @=
	      Тип: Бинарный

	      Ассоциативность: Справа

	      Описание: присваивание

       == <= >= != < >
	      Тип: Бинарный

	      Ассоциативность: Слева

	      Описание: реляционные

       &&     Тип: Бинарный

	      Ассоциативность: Слева

	      Описание: логическое и

       ||     Тип: Бинарный

	      Ассоциативность: Слева

	      Описание: логическое или

       Операторы будут описаны более подробно ниже.

       ++ --  Префиксные и постфиксные операторы инкремента и декремента ведут себя
	      точно так же, как в C.  Они требуют именованного выражения
	      (см. подраздел Named Expressions) в качестве операнда.

	      Префиксные версии этих операторов более эффективны; используйте их, где возможно.

       -      Оператор отрицания возвращает 0, если пользователь пытается отрицать любое выражение со значением 0.  В противном случае, возвращается копия выражения с перевернутым знаком.

       !      Оператор логического не возвращает 1, если выражение равно 0, или 0
	      в противном случае.

	      Предупреждение: Этот оператор имеет другой приоритет, чем эквивалентный оператор в GNU bc(1) и других реализациях bc(1)!

	      Это нестандартное расширение.

       $      Оператор усечения возвращает копию данного выражения
	      без всего его масштаба.

	      Это нестандартное расширение.

       @      Оператор установки точности принимает два выражения и возвращает копию
	      первого с масштабом, равным значению второго выражения.  Это могло бы означать, что число возвращается без изменений (если масштаб первого выражения совпадает со значением второго выражения), расширено (если оно меньше) или усечено (если оно больше).

	      Второе выражение должно быть целым (без масштаба) и неотрицательным.

	      Это нестандартное расширение.

       ^      Оператор возведения в степень (не оператор исключающего или, как это было бы в C) принимает два выражения и возводит первое в степень значения второго.  Масштаб результата равен scale.

	      Второе выражение должно быть целым (без масштаба), и если оно
	      отрицательное, первое значение должно быть ненулевым.

       *      Оператор умножения принимает два выражения, умножает их,
	      и возвращает произведение.  Если a - масштаб первого выражения, а b - масштаб второго выражения, масштаб результата равен min(a+b,max(scale,a,b)), где min() и max() возвращают очевидные значения.

       /      Оператор деления принимает два выражения, делит их и возвращает частное.  Масштаб результата будет равен значению scale.

	      Второе выражение должно быть ненулевым.

       %      Оператор модуля принимает два выражения, a и b, и оценивает их путем 1) Вычисления a/b до текущего масштаба и 2) Использования результата шага 1 для расчета a-(a/b)*b до масштаба
	      max(scale+scale(b),scale(a)).

	      Второе выражение должно быть ненулевым.

       +      Оператор сложения принимает два выражения, a и b, и возвращает сумму, с масштабом, равным максимуму масштабов a и b.

       -      Оператор вычитания принимает два выражения, a и b, и возвращает разность, с масштабом, равным максимуму масштабов a и b.

       <<     Оператор сдвига влево принимает два выражения, a и b, и возвращает копию значения a с десятичной точкой, перемещенной b
	      позиций вправо.

	      Второе выражение должно быть целым (без масштаба) и неотрицательным.

	      Это нестандартное расширение.

       >>     Оператор сдвига вправо принимает два выражения, a и b, и возвращает копию значения a с десятичной точкой, перемещенной b
	      позиций влево.

	      Второе выражение должно быть целым (без масштаба) и неотрицательным.

	      Это нестандартное расширение.

       = <<= >>= += -= *= /= %= ^= @=
	      Операторы присваивания принимают два выражения, a и b, где a
	      является именованным выражением (см. подраздел Named Expressions).

	      Для =, b копируется и результат присваивается a.  Для всех
	      остальных, a и b применяются как операнды к соответствующему
	      арифметическому оператору и результат присваивается a.

	      Операторы присваивания, соответствующие операторам, которые являются расширениями, сами по себе являются нестандартными расширениями.

       == <= >= != < >
	      Реляционные операторы сравнивают два выражения, a и b, и если отношение верно,
	      согласно семантике языка C, результат равен 1.  В противном случае, он равен 0.

	      Обратите внимание, что в отличие от C, эти операторы имеют меньший приоритет,
	      чем операторы присваивания, что означает, что a=b>c интерпретируется как (a=b)>c.

	      Кроме того, в отличие от того, что требует стандарт (см. раздел STANDARDS), эти операторы могут появляться где угодно, где могут использоваться другие выражения.  Это разрешение является нестандартным расширением.

       &&     Оператор логического и принимает два выражения и возвращает 1, если оба выражения ненулевые, 0 в противном случае.

	      Это не короткозамкнутый оператор.

	      Это нестандартное расширение.

       ||     Оператор логического или принимает два выражения и возвращает 1, если одно из выражений ненулевое, 0 в противном случае.

	      Это не короткозамкнутый оператор.

	      Это нестандартное расширение.

   Statements
       Следующие элементы являются операторами:

	1. E

	2. { S ; ...  ; S }

	3. if ( E ) S

	4. if ( E ) S else S

	5. while ( E ) S

	6. for ( E ; E ; E ) S

	7. Пустой оператор

	8. break

	9. continue

       10. quit

       11. halt

       12. limits

       13. Строка символов, заключенная в двойные кавычки

       14. print E , ...  , E

       15. stream E , ...  , E

       16. I(), I(E), I(E, E) и так далее, где I является идентификатором для void
	   функции (см. подраздел Void Functions раздела FUNCTIONS).  Аргумент(ы) E также может быть массивами в форме I[], которые
	   автоматически преобразуются в ссылки на массивы (см.
	   подраздел Array References раздела FUNCTIONS), если соответствующий параметр в определении функции - ссылка на массив.

       Пункты 4, 9, 11, 12, 14, 15 и 16 являются нестандартными расширениями.

       Кроме того, как нестандартное расширение, любое или все выражения в заголовке цикла for могут быть omitted.  Если условие (второе выражение) omitted, предполагается, что оно равно константе 1.

       Оператор break заставляет цикл прекратить итерацию и продолжить выполнение сразу после цикла.  Это разрешено только в циклах.

       Оператор continue заставляет итерацию цикла прекратить рано и вернуться
       к началу цикла, включая проверку условия цикла.
       Это разрешено только в циклах.

       Оператор if else работает так же, как в C.

       Оператор quit заставляет bc(1) выйти, даже если он на ветке, которая
       не будет выполнена (это команда времени компиляции).

       Предупреждение: Поведение этого bc(1) на quit немного отличается от других реализаций bc(1).  Другие реализации bc(1) выйдут как только закончат разбор строки, на которой команда quit.  Этот bc(1) выполнит любые завершенные и исполняемые операторы, которые происходят перед оператором quit перед выходом.

       В других словах, для кода bc(1) ниже:

	      for (i = 0; i < 3; ++i) i; quit

       Другие реализации bc(1) ничего не напечатают, а этот bc(1)
       напечатает 0, 1 и 2 на последовательных строках перед выходом.

       Оператор halt заставляет bc(1) выйти, если он выполнен.  (В отличие
       от quit, если он на ветке оператора if, которая не выполняется,
       bc(1) не выйдет.)

       Оператор limits печатает ограничения, которым подчиняется этот bc(1).
       Это как оператор quit в том, что это команда времени компиляции.

       Выражение само по себе оценивается и печатается, за ним следует новая
       строка.

       И научная нотация, и инженерная нотация доступны для
       печати результатов выражений.  Научная нотация активируется
       присваиванием 0 obase, а инженерная нотация активируется присваиванием 1 obase.  Чтобы деактивировать их, просто присвойте другое значение obase.

       Научная нотация и инженерная нотация отключены, если bc(1) запущен с опциями -s или -w командной строки (или эквивалентами).

       Печать чисел в научной нотации и/или инженерной нотации является
       нестандартным расширением.

   Strings
       Если строки появляются как оператор сами по себе, они печатаются без
       последующей новой строки.

       Кроме того, строки могут быть присвоены переменным и элементам массива.  Их также можно передать функциям в переменных параметрах.

       Если любой оператор, который ожидает строку, дан переменную, которой была присвоена строка, оператор действует так, как будто он получил строку.

       Если любая математическая операция предпринимается на строке или переменной или элементе массива, которому была присвоена строка, возникает ошибка, и bc(1)
       сбрасывается (см. раздел RESET).

       Присваивание строк переменным и элементам массива и передача их функциям являются нестандартными расширениями.

   Print Statement
       "Выражения" в операторе print также могут быть строками.  Если они
       являются, существуют последовательности escape с обратным слэшем, которые интерпретируются
       специально.  Какие это последовательности и что они вызывают печать, приведено ниже:

       \a: \a

       \b: \b

       \\: \

       \e: \

       \f: \f

       \n: \n

       \q: “

       \r: \r

       \t: \t

       Любые другие символы, следующие за обратным слэшем, вызывают печать обратного слэша и символа как есть.

       Любое невыражение строки в операторе print будет присвоено
       last, как и любое другое выражение, которое печатается.

   Stream Statement
       Выражения в операторе stream также могут быть строками.

       Если оператору stream дана строка, он печатает строку так, как будто
       строка появилась как свой собственный оператор.  Иными словами, оператор stream печатает строки нормально, без новой строки.

       Если оператору stream дано число, копия его усекается и
       вычисляется его абсолютное значение.  Результат затем печатается так, как будто
       obase равно 256 и каждая цифра интерпретируется как 8-битный символ ASCII,
       делая его потоком байтов.

   Order of Evaluation
       Все выражения в операторе оцениваются слева направо, кроме как необходимо для поддержания порядка операций.  Это означает, например,
       предполагая, что i равно 0, в выражении

	      a[i++] = i++

       первый (или 0-й) элемент a устанавливается в 1, и i равно 2 в конце
       выражения.

       Это включает аргументы функций.  Таким образом, предполагая, что i равно 0, это
       означает, что в выражении

	      x(i++, i++)

       первый аргумент, переданный x(), равен 0, а второй аргумент равен 1,
       в то время как i равно 2 перед тем, как функция начнет выполняться.

FUNCTIONS
       Определения функций выглядят так:

	      define I(I,...,I){
		  auto I,...,I
		  S;...;S
		  return(E)
	      }

       Любое I в списке параметров или списке auto может быть заменено на I[] для
       превращения параметра или auto var в массив, и любое I в списке параметров
       может быть заменено на *I[] для превращения параметра в ссылку на массив.
       Вызывающие функции, которые принимают ссылки на массивы, не должны ставить звездочку в вызове; они должны быть вызваны с просто I[] как нормальные параметры массива и будут автоматически преобразованы в ссылки.

       Как нестандартное расширение, открывающая фигурная скобка оператора define может появляться на следующей строке.

       Как нестандартное расширение, оператор return также может быть в одной из
       следующих форм:

       1. return

       2. return ( )

       3. return E

       Первые два, или не указание оператора return, эквивалентно
       return (0), если функция не является void функцией (см. подраздел Void Functions ниже).

   Void Functions
       Функции также могут быть void функциями, определенными так:

	      define void I(I,...,I){
		  auto I,...,I
		  S;...;S
		  return
	      }

       Их можно использовать только как отдельные выражения, где такое выражение будет напечатано в одиночку, кроме в операторе print.

       Void функции могут использовать только первые два оператора return, перечисленных
       выше.  Они также могут omitted оператор return полностью.

       Слово "void" не трактуется как ключевое слово; все еще возможно
       иметь переменные, массивы и функции с именем void.  Слово "void" трактуется специально только сразу после ключевого слова define.

       Это нестандартное расширение.

   Array References
       Для любого массива в списке параметров, если массив объявлен в форме

	      *I[]

       это ссылка.  Любые изменения массива в функции отражаются,
       когда функция возвращается, на массив, который был передан.

       В остальном, все аргументы функций передаются по значению.

       Это нестандартное расширение.

LIBRARY
       Все функции ниже, включая функции в расширенной математической библиотеке (см. подраздел Extended Library ниже), доступны
       когда даны флаги командной строки -l или --mathlib, кроме того, что расширенная математическая библиотека недоступна, когда даны опции -s, -w или эквиваленты.

   Standard Library
       Стандарт (см. раздел STANDARDS) определяет следующие функции для математической библиотеки:

       s(x)   Возвращает синус x, предполагая, что x в радианах.

	      Это трансцендентная функция (см. подраздел Transcendental Func‐
	      tions ниже).

       c(x)   Возвращает косинус x, предполагая, что x в радианах.

	      Это трансцендентная функция (см. подраздел Transcendental Func‐
	      tions ниже).

       a(x)   Возвращает арктангенс x, в радианах.

	      Это трансцендентная функция (см. подраздел Transcendental Func‐
	      tions ниже).

       l(x)   Возвращает натуральный логарифм x.

	      Это трансцендентная функция (см. подраздел Transcendental Func‐
	      tions ниже).

       e(x)   Возвращает математическую константу e, возведенную в степень x.

	      Это трансцендентная функция (см. подраздел Transcendental Func‐
	      tions ниже).

       j(x, n)
	      Возвращает бessel целого порядка n (усеченное) x.

	      Это трансцендентная функция (см. подраздел Transcendental Func‐
	      tions ниже).

   Extended Library
       Расширенная библиотека не загружается, когда даны опции -s/--standard или -w/--warn,
       поскольку они не являются частью библиотеки, определенной стандартом (см. раздел STANDARDS).

       Расширенная библиотека является нестандартным расширением.

       p(x, y)
	      Вычисляет x в степени y, даже если y не целое, и
	      возвращает результат до текущего масштаба.

	      Это ошибка, если y отрицательное и x равно 0.

	      Это трансцендентная функция (см. подраздел Transcendental Func‐
	      tions ниже).

       r(x, p)
	      Возвращает x, округленное до p десятичных знаков в соответствии с режимом округления половина от 0
	      (https://en.wikipedia.org/wiki/Round‐
	      ing#Round_half_away_from_zero).

       ceil(x, p)
	      Возвращает x, округленное до p десятичных знаков в соответствии с режимом округления от 0 (https://en.wikipedia.org/wiki/Round‐
	      ing#Rounding_away_from_zero).

       f(x)   Возвращает факториал усеченного абсолютного значения x.

       max(a, b)
	      Возвращает a, если a больше b; в противном случае, возвращает b.

       min(a, b)
	      Возвращает a, если a меньше b; в противном случае, возвращает b.

       perm(n, k)
	      Возвращает перестановку усеченного абсолютного значения n усеченного абсолютного значения k, если k <= n.  Если нет, возвращает 0.

       comb(n, k)
	      Возвращает комбинацию усеченного абсолютного значения n усеченного абсолютного значения k, если k <= n.  Если нет, возвращает 0.

       fib(n) Возвращает число Фибоначчи усеченного абсолютного значения n.

       l2(x)  Возвращает логарифм по основанию 2 x.

	      Это трансцендентная функция (см. подраздел Transcendental Func‐
	      tions ниже).

       l10(x) Возвращает логарифм по основанию 10 x.

	      Это трансцендентная функция (см. подраздел Transcendental Func‐
	      tions ниже).

       log(x, b)
	      Возвращает логарифм по основанию b x.

	      Это трансцендентная функция (см. подраздел Transcendental Func‐
	      tions ниже).

       cbrt(x)
	      Возвращает кубический корень x.

       root(x, n)
	      Вычисляет усеченное значение n, r, и возвращает r-й корень
	      x до текущего масштаба.

	      Если r равно 0 или отрицательному, это вызывает ошибку, и bc(1)
	      сбрасывается (см. раздел RESET).  Это также вызывает ошибку и
	      сбрасывает bc(1), если r четное и x отрицательное.

       gcd(a, b)
	      Возвращает наибольший общий делитель (фактор) усеченного
	      абсолютного значения a и усеченного абсолютного значения b.

       lcm(a, b)
	      Возвращает наименьшее общее кратное усеченного абсолютного
	      значения a и усеченного абсолютного значения b.

       pi(p)  Возвращает pi до p десятичных знаков.

	      Это трансцендентная функция (см. подраздел Transcendental Func‐
	      tions ниже).

       t(x)   Возвращает тангенс x, предполагая, что x в радианах.

	      Это трансцендентная функция (см. подраздел Transcendental Func‐
	      tions ниже).

       a2(y, x)
	      Возвращает арктангенс y/x, в радианах.  Если и y, и x равны 0, это вызывает ошибку, и bc(1) сбрасывается (см.
	      раздел RESET).  В противном случае, если x больше 0, возвращается a(y/x).  Если x меньше 0, и y больше или равно 0, возвращается a(y/x)+pi.  Если x меньше 0, и y меньше 0, возвращается a(y/x)-pi.  Если x равно 0, и y больше 0, возвращается pi/2.  Если x равно 0, и y меньше 0, возвращается -pi/2.

	      Эта функция такая же, как функция atan2() во многих языках
	      программирования.

	      Это трансцендентная функция (см. подраздел Transcendental Func‐
	      tions ниже).

       sin(x) Возвращает синус x, предполагая, что x в радианах.

	      Это псевдоним s(x).

	      Это трансцендентная функция (см. подраздел Transcendental Func‐
	      tions ниже).

       cos(x) Возвращает косинус x, предполагая, что x в радианах.

	      Это псевдоним c(x).

	      Это трансцендентная функция (см. подраздел Transcendental Func‐
	      tions ниже).

       tan(x) Возвращает тангенс x, предполагая, что x в радианах.

	      Если x равно 1 или -1, это вызывает ошибку, и bc(1)
	      сбрасывается (см. раздел RESET).

	      Это псевдоним t(x).

	      Это трансцендентная функция (см. подраздел Transcendental Func‐
	      tions ниже).

       atan(x)
	      Возвращает арктангенс x, в радианах.

	      Это псевдоним a(x).

	      Это трансцендентная функция (см. подраздел Transcendental Func‐
	      tions ниже).

       atan2(y, x)
	      Возвращает арктангенс y/x, в радианах.  Если и y, и x равны 0, это вызывает ошибку, и bc(1) сбрасывается (см.
	      раздел RESET).  В противном случае, если x больше 0, возвращается a(y/x).  Если x меньше 0, и y больше или равно 0, возвращается a(y/x)+pi.  Если x меньше 0, и y меньше 0, возвращается a(y/x)-pi.  Если x равно 0, и y больше 0, возвращается pi/2.  Если x равно 0, и y меньше 0, возвращается -pi/2.

	      Эта функция такая же, как функция atan2() во многих языках
	      программирования.

	      Это псевдоним a2(y, x).

	      Это трансцендентная функция (см. подраздел Transcendental Func‐
	      tions ниже).

       r2d(x) Преобразует x из радиан в градусы и возвращает результат.

	      Это трансцендентная функция (см. подраздел Transcendental Func‐
	      tions ниже).

       d2r(x) Преобразует x из градусов в радианы и возвращает результат.

	      Это трансцендентная функция (см. подраздел Transcendental Func‐
	      tions ниже).

       frand(p)
	      Генерирует псевдослучайное число между 0 (включительно) и 1
	      (исключительно) с количеством десятичных цифр после десятичной точки, равным усеченному абсолютному значению p.  Если p не 0, то вызов этой функции изменит значение seed.  Если p равно 0, возвращается 0, и seed не изменяется.

       ifrand(i, p)
	      Генерирует псевдослучайное число, которое между 0 (включительно)
	      и усеченным абсолютным значением i (исключительно) с количеством десятичных цифр после десятичной точки, равным усеченному абсолютному значению p.  Если абсолютное значение i больше или равно 2, и p не 0, то вызов этой функции изменит значение seed; в противном случае, возвращается 0, и seed не изменяется.

       i2rand(a, b)
	      Берет усеченное значение a и b и использует их как включительные
	      границы для генерации псевдослучайного целого.  Если разница усеченных значений a и b равна 0, то усеченное значение возвращается, и seed не изменяется.  В противном случае, эта функция изменит значение seed.

       srand(x)
	      Возвращает x с перевернутым знаком с вероятностью 0.5.  Иными словами, оно случайизирует знак x.

       brand()
	      Возвращает случайное логическое значение (либо 0, либо 1).

       band(a, b)
	      Берет усеченное абсолютное значение и b и вычисляет и возвращает результат операции побитового и между ними.

	      Если вы хотите использовать аргументы со знаком двухвесового дополнения, используйте s2u(x)
	      для преобразования.

       bor(a, b)
	      Берет усеченное абсолютное значение и b и вычисляет и возвращает результат операции побитового или между ними.

	      Если вы хотите использовать аргументы со знаком двухвесового дополнения, используйте s2u(x)
	      для преобразования.

       bxor(a, b)
	      Берет усеченное абсолютное значение и b и вычисляет и возвращает результат операции побитового исключающего или между ними.

	      Если вы хотите использовать аргументы со знаком двухвесового дополнения, используйте s2u(x)
	      для преобразования.

       bshl(a, b)
	      Берет усеченное абсолютное значение и b и вычисляет и возвращает результат a, сдвинутого влево на b позиций.

	      Если вы хотите использовать аргументы со знаком двухвесового дополнения, используйте s2u(x)
	      для преобразования.

       bshr(a, b)
	      Берет усеченное абсолютное значение и b и вычисляет и возвращает усеченный результат a, сдвинутого вправо на b позиций.

	      Если вы хотите использовать аргументы со знаком двухвесового дополнения, используйте s2u(x)
	      для преобразования.

       bnotn(x, n)
	      Берет усеченное абсолютное значение x и выполняет побитовое не
	      так, как будто у него такое же количество байтов, как у усеченного абсолютного значения n.

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       bnot8(x)
	      Выполняет побитовое не усеченного абсолютного значения x так,
	      как будто у него 8 бинарных цифр (1 беззнаковый байт).

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       bnot16(x)
	      Выполняет побитовое не усеченного абсолютного значения x так,
	      как будто у него 16 бинарных цифр (2 беззнаковых байта).

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       bnot32(x)
	      Выполняет побитовое не усеченного абсолютного значения x так,
	      как будто у него 32 бинарных цифр (4 беззнаковых байта).

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       bnot64(x)
	      Выполняет побитовое не усеченного абсолютного значения x так,
	      как будто у него 64 бинарных цифр (8 беззнаковых байтов).

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       bnot(x)
	      Выполняет побитовое не усеченного абсолютного значения x так,
	      как будто у него минимальное количество степеней степени два беззнаковых байтов.

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       brevn(x, n)
	      Выполняет реверс битов усеченного абсолютного значения x так,
	      как будто у него такое же количество 8-битных байтов, как у усеченного абсолютного значения n.

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       brev8(x)
	      Выполняет реверс битов усеченного абсолютного значения x так,
	      как будто у него 8 бинарных цифр (1 беззнаковый байт).

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       brev16(x)
	      Выполняет реверс битов усеченного абсолютного значения x так,
	      как будто у него 16 бинарных цифр (2 беззнаковых байта).

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       brev32(x)
	      Выполняет реверс битов усеченного абсолютного значения x так,
	      как будто у него 32 бинарных цифр (4 беззнаковых байта).

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       brev64(x)
	      Выполняет реверс битов усеченного абсолютного значения x так,
	      как будто у него 64 бинарных цифр (8 беззнаковых байтов).

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       brev(x)
	      Выполняет реверс битов усеченного абсолютного значения x так,
	      как будто у него минимальное количество степеней степени два беззнаковых байтов.

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       broln(x, p, n)
	      Выполняет левый побитовый ротацию усеченного абсолютного значения
	      x, так, как будто у него такое же количество беззнаковых 8-битных байтов
	      как у усеченного абсолютного значения n, на количество позиций
	      равное усеченному абсолютному значению p modded по 2 в степени количества бинарных цифр в n 8-битных байтах.

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       brol8(x, p)
	      Выполняет левый побитовый ротацию усеченного абсолютного значения
	      x, так, как будто у него 8 бинарных цифр (1 беззнаковый байт), на количество позиций равное усеченному абсолютному значению p modded по 2 в степени 8.

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       brol16(x, p)
	      Выполняет левый побитовый ротацию усеченного абсолютного значения
	      x, так, как будто у него 16 бинарных цифр (2 беззнаковых байта), на количество позиций равное усеченному абсолютному значению p modded по 2 в степени 16.

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       brol32(x, p)
	      Выполняет левый побитовый ротацию усеченного абсолютного значения
	      x, так, как будто у него 32 бинарных цифр (4 беззнаковых байта), на количество позиций равное усеченному абсолютному значению p modded по 2 в степени 32.

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       brol64(x, p)
	      Выполняет левый побитовый ротацию усеченного абсолютного значения
	      x, так, как будто у него 64 бинарных цифр (8 беззнаковых байтов), на количество позиций равное усеченному абсолютному значению p modded по 2 в степени 64.

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       brol(x, p)
	      Выполняет левый побитовый ротацию усеченного абсолютного значения
	      x, так, как будто у него минимальное количество степеней степени два беззнаковых
	      8-битных байтов, на количество позиций равное усеченному абсолютному значению p modded по 2 в степени количества бинарных цифр в минимальном количестве 8-битных байтов.

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       brorn(x, p, n)
	      Выполняет правый побитовый ротацию усеченного абсолютного значения
	      x, так, как будто у него такое же количество беззнаковых 8-битных байтов
	      как у усеченного абсолютного значения n, на количество позиций
	      равное усеченному абсолютному значению p modded по 2 в степени количества бинарных цифр в n 8-битных байтах.

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       bror8(x, p)
	      Выполняет правый побитовый ротацию усеченного абсолютного значения
	      x, так, как будто у него 8 бинарных цифр (1 беззнаковый байт), на количество позиций равное усеченному абсолютному значению p modded по 2 в степени 8.

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       bror16(x, p)
	      Выполняет правый побитовый ротацию усеченного абсолютного значения
	      x, так, как будто у него 16 бинарных цифр (2 беззнаковых байта), на количество позиций равное усеченному абсолютному значению p modded по 2 в степени 16.

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       bror32(x, p)
	      Выполняет правый побитовый ротацию усеченного абсолютного значения
	      x, так, как будто у него 32 бинарных цифр (4 беззнаковых байта), на количество позиций равное усеченному абсолютному значению p modded по 2 в степени 32.

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       bror64(x, p)
	      Выполняет правый побитовый ротацию усеченного абсолютного значения
	      x, так, как будто у него 64 бинарных цифр (8 беззнаковых байтов), на количество позиций равное усеченному абсолютному значению p modded по 2 в степени 64.

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       bror(x, p)
	      Выполняет правый побитовый ротацию усеченного абсолютного значения
	      x, так, как будто у него минимальное количество степеней степени два беззнаковых
	      8-битных байтов, на количество позиций равное усеченному абсолютному значению p modded по 2 в степени количества бинарных цифр в минимальном количестве 8-битных байтов.

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       bmodn(x, n)
	      Возвращает модуль усеченного абсолютного значения x по 2 в
	      степени умножения усеченного абсолютного значения n и 8.

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       bmod8(x, n)
	      Возвращает модуль усеченного абсолютного значения x по 2 в
	      степени 8.

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       bmod16(x, n)
	      Возвращает модуль усеченного абсолютного значения x по 2 в
	      степени 16.

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       bmod32(x, n)
	      Возвращает модуль усеченного абсолютного значения x по 2 в
	      степени 32.

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       bmod64(x, n)
	      Возвращает модуль усеченного абсолютного значения x по 2 в
	      степени 64.

	      Если вы хотите использовать аргумент со знаком двухвесового дополнения, используйте
	      s2u(x) для преобразования.

       bunrev(t)
	      Предполагает, что t является числом с реверсированными битами с дополнительным установленным битом на одну позицию более значимую, чем реальный самый значимый бит (который был наименее значимым битом в исходном числе).  Это число реверсируется и возвращается без дополнительного установленного бита.

	      Эта функция используется для реализации других побитовых функций; она не предназначена для использования пользователями, но может быть.

       plz(x) Если x не равно 0 и больше -1 и меньше 1, оно
	      печатается с ведущим нулем, независимо от использования опции -z
	      (см. раздел OPTIONS) и без последующей новой строки.

	      В противном случае, x печатается нормально, без последующей новой строки.

       plznl(x)
	      Если x не равно 0 и больше -1 и меньше 1, оно
	      печатается с ведущим нулем, независимо от использования опции -z
	      (см. раздел OPTIONS) и с последующей новой строкой.

	      В противном случае, x печатается нормально, с последующей новой строкой.

       pnlz(x)
	      Если x не равно 0 и больше -1 и меньше 1, оно
	      печатается без ведущего нуля, независимо от использования опции -z
	      (см. раздел OPTIONS) и без последующей новой строки.

	      В противном случае, x печатается нормально, без последующей новой строки.

       pnlznl(x)
	      Если x не равно 0 и больше -1 и меньше 1, оно
	      печатается без ведущего нуля, независимо от использования опции -z
	      (см. раздел OPTIONS) и с последующей новой строкой.

	      В противном случае, x печатается нормально, с последующей новой строкой.

       ubytes(x)
	      Возвращает количество беззнаковых целочисленных байтов, необходимых для хранения
	      усеченного абсолютного значения x.

       sbytes(x)
	      Возвращает количество знаковых, двухвесовых дополнений целочисленных байтов, необходимых для хранения
	      усеченного значения x.

       s2u(x) Возвращает x, если оно неотрицательное.  Если оно отрицательное, то вычисляет, что x было бы как целое со знаком двухвесового дополнения и возвращает неотрицательное целое, которое имело бы то же представление в бинарном виде.

       s2un(x,n)
	      Возвращает x, если оно неотрицательное.  Если оно отрицательное, то вычисляет, что x было бы как целое со знаком двухвесового дополнения с n байтами и возвращает неотрицательное целое, которое имело бы то же представление в бинарном виде.  Если x не помещается в n знаковых двухвесовых байтов, оно усекается.

       hex(x) Выводит шестнадцатеричное (база 16) представление x.

	      Это void функция (см. подраздел Void Functions раздела
	      FUNCTIONS).

       binary(x)
	      Выводит бинарное (база 2) представление x.

	      Это void функция (см. подраздел Void Functions раздела
	      FUNCTIONS).

       output(x, b)
	      Выводит базу b представление x.

	      Это void функция (см. подраздел Void Functions раздела
	      FUNCTIONS).

       uint(x)
	      Выводит представление, в бинарном и шестнадцатеричном виде, x как
	      беззнаковое целое в как можно меньшем количестве степеней степени два байтов.  Оба вывода разделены на байты, разделенные пробелами.

	      Если x не целое или отрицательное, выводится сообщение об ошибке вместо этого, но bc(1) не сбрасывается (см. раздел RESET).

	      Это void функция (см. подраздел Void Functions раздела
	      FUNCTIONS).

       int(x) Выводит представление, в бинарном и шестнадцатеричном виде, x как
	      знаковое, двухвесовое дополнение целое в как можно меньшем количестве степеней степени два байтов.  Оба вывода разделены на байты, разделенные пробелами.

	      Если x не целое, выводится сообщение об ошибке вместо этого, но
	      bc(1) не сбрасывается (см. раздел RESET).

	      Это void функция (см. подраздел Void Functions раздела
	      FUNCTIONS).

       uintn(x, n)
	      Выводит представление, в бинарном и шестнадцатеричном виде, x как
	      беззнаковое целое в n байтах.  Оба вывода разделены на
	      байты, разделенные пробелами.

	      Если x не целое, отрицательное или не помещается в n байты,
	      выводится сообщение об ошибке вместо этого, но bc(1) не сбрасывается (см. раздел RESET).

	      Это void функция (см. подраздел Void Functions раздела
	      FUNCTIONS).

       intn(x, n)
	      Выводит представление, в бинарном и шестнадцатеричном виде, x как знаковое, двухвесовое дополнение целое в n байтах.  Оба вывода разделены на байты, разделенные пробелами.

	      Если x не целое или не помещается в n байты, выводится сообщение об ошибке вместо этого, но bc(1) не сбрасывается (см. раздел RESET).

	      Это void функция (см. подраздел Void Functions раздела
	      FUNCTIONS).

       uint8(x)
	      Выводит представление, в бинарном и шестнадцатеричном виде, x как
	      беззнаковое целое в 1 байте.  Оба вывода разделены на байты, разделенные пробелами.

	      Если x не целое, отрицательное или не помещается в 1 байт,
	      выводится сообщение об ошибке вместо этого, но bc(1) не сбрасывается (см. раздел RESET).

	      Это void функция (см. подраздел Void Functions раздела
	      FUNCTIONS).

       int8(x)
	      Выводит представление, в бинарном и шестнадцатеричном виде, x как знаковое, двухвесовое дополнение целое в 1 байте.  Оба вывода разделены на байты, разделенные пробелами.

	      Если x не целое или не помещается в 1 байт, выводится сообщение об ошибке вместо этого, но bc(1) не сбрасывается (см. раздел RESET).

	      Это void функция (см. подраздел Void Functions раздела
	      FUNCTIONS).

       uint16(x)
	      Выводит представление, в бинарном и шестнадцатеричном виде, x как
	      беззнаковое целое в 2 байтах.  Оба вывода разделены на байты, разделенные пробелами.

	      Если x не целое, отрицательное или не помещается в 2 байта,
	      выводится сообщение об ошибке вместо этого, но bc(1) не сбрасывается (см. раздел RESET).

	      Это void функция (см. подраздел Void Functions раздела
	      FUNCTIONS).

       int16(x)
	      Выводит представление, в бинарном и шестнадцатеричном виде, x как знаковое, двухвесовое дополнение целое в 2 байтах.  Оба вывода разделены на байты, разделенные пробелами.

	      Если x не целое или не помещается в 2 байта, выводится сообщение об ошибке вместо этого, но bc(1) не сбрасывается (см. раздел RESET).

	      Это void функция (см. подраздел Void Functions раздела
	      FUNCTIONS).

       uint32(x)
	      Выводит представление, в бинарном и шестнадцатеричном виде, x как
	      беззнаковое целое в 4 байтах.  Оба вывода разделены на байты, разделенные пробелами.

	      Если x не целое, отрицательное или не помещается в 4 байта,
	      выводится сообщение об ошибке вместо этого, но bc(1) не сбрасывается (см. раздел RESET).

	      Это void функция (см. подраздел Void Functions раздела
	      FUNCTIONS).

       int32(x)
	      Выводит представление, в бинарном и шестнадцатеричном виде, x как знаковое, двухвесовое дополнение целое в 4 байтах.  Оба вывода разделены на байты, разделенные пробелами.

	      Если x не целое или не помещается в 4 байта, выводится сообщение об ошибке вместо этого, но bc(1) не сбрасывается (см. раздел RESET).

	      Это void функция (см. подраздел Void Functions раздела
	      FUNCTIONS).

       uint64(x)
	      Выводит представление, в бинарном и шестнадцатеричном виде, x как
	      беззнаковое целое в 8 байтах.  Оба вывода разделены на байты, разделенные пробелами.

	      Если x не целое, отрицательное или не помещается в 8 байта,
	      выводится сообщение об ошибке вместо этого, но bc(1) не сбрасывается (см. раздел RESET).

	      Это void функция (см. подраздел Void Functions раздела
	      FUNCTIONS).

       int64(x)
	      Выводит представление, в бинарном и шестнадцатеричном виде, x как знаковое, двухвесовое дополнение целое в 8 байтах.  Оба вывода разделены на байты, разделенные пробелами.

	      Если x не целое или не помещается в 8 байта, выводится сообщение об ошибке вместо этого, но bc(1) не сбрасывается (см. раздел RESET).

	      Это void функция (см. подраздел Void Functions раздела
	      FUNCTIONS).

       hex_uint(x, n)
	      Выводит представление усеченного абсолютного значения x
	      как беззнаковое целое в шестнадцатеричном виде с использованием n байтов.  Не все значение будет выведено, если n слишком маленькое.

	      Это void функция (см. подраздел Void Functions раздела
	      FUNCTIONS).

       binary_uint(x, n)
	      Выводит представление усеченного абсолютного значения x
	      как беззнаковое целое в бинарном виде с использованием n байтов.  Не все значение будет выведено, если n слишком маленькое.

	      Это void функция (см. подраздел Void Functions раздела
	      FUNCTIONS).

       output_uint(x, n)
	      Выводит представление усеченного абсолютного значения x
	      как беззнаковое целое в текущей obase (см. раздел SYNTAX)
	      с использованием n байтов.  Не все значение будет выведено, если n слишком маленькое.

	      Это void функция (см. подраздел Void Functions раздела
	      FUNCTIONS).

       output_byte(x, i)
	      Выводит байт i усеченного абсолютного значения x, где 0 -
	      наименее значимый байт и number_of_bytes - 1 - наиболее значимый байт.

	      Это void функция (см. подраздел Void Functions раздела
	      FUNCTIONS).

   Transcendental Functions
       Все трансцендентные функции могут возвращать слегка неточные результаты, до 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place).  Это неизбежно, и статья по адресу https://people.eecs.berke‐
       ley.edu/~wkahan/LOG10HAF.TXT объясняет, почему невозможно и ненужно вычислять точные результаты для трансцендентных функций.

       Из-за возможной неточности, я рекомендую, чтобы пользователи вызывали эти
       функции с точностью (scale), установленной как минимум на 1 выше, чем необходимо.  Если точные результаты абсолютно необходимы, пользователи могут удвоить точность (scale) и затем усечь.

       Трансцендентные функции в стандартной математической библиотеке:

       • s(x)

       • c(x)

       • a(x)

       • l(x)

       • e(x)

       • j(x, n)

       Трансцендентные функции в расширенной математической библиотеке:

       • l2(x)

       • l10(x)

       • log(x, b)

       • pi(p)

       • t(x)

       • a2(y, x)

       • sin(x)

       • cos(x)

       • tan(x)

       • atan(x)

       • atan2(y, x)

       • r2d(x)

       • d2r(x)

RESET
       Когда bc(1) встречает ошибку или сигнал, для которого у него есть ненулевой обработчик, он сбрасывается.  Это означает, что несколько вещей происходит.

       Во-первых, любые функции, которые выполняются, останавливаются и снимаются со стека.  Поведение не похоже на исключения в языках программирования.  Затем точка выполнения устанавливается так, что любой код, ожидающий выполнения (после того, как все функции вернулись), пропускается.

       Таким образом, когда bc(1) сбрасывается, он пропускает любой оставшийся код, ожидающий выполнения.  Затем, если это интерактивный режим и ошибка не была фатальной ошибкой (см. раздел EXIT STATUS), он запрашивает больше ввода; в противном случае,
       он выходит с соответствующим кодом возврата.

       Обратите внимание, что это поведение сброса отличается от GNU bc(1), который
       пытается начать выполнять оператор сразу после того, который вызвал ошибку.

PERFORMANCE
       Большинство реализаций bc(1) используют типы char для вычисления значения 1
       десятичной цифры за раз, но это может быть медленно.  Этот bc(1) делает что-то другое.

       Он использует большие целые числа для вычисления более чем 1 десятичной цифры за раз.  Если построен в среде, где BC_LONG_BIT (см. раздел LIMITS) - 64, то каждое целое имеет 9 десятичных цифр.  Если построен в среде, где BC_LONG_BIT - 32, то каждое целое имеет 4 десятичных цифры.  Это значение (количество десятичных цифр на большое целое) называется BC_BASE_DIGS.

       Фактические значения BC_LONG_BIT и BC_BASE_DIGS можно запросить с
       оператором limits.

       Кроме того, этот bc(1) использует еще большее целое для проверки переполнения.  Тип целого зависит от значения BC_LONG_BIT, но всегда как минимум в два раза больше, чем тип целого, используемый для хранения цифр.

LIMITS
       Следующие являются ограничениями на bc(1):

       BC_LONG_BIT
	      Количество битов в типе long в среде, где
	      bc(1) был построен.  Это определяет, сколько десятичных цифр может быть
	      сохранено в одном большом целом (см. раздел PERFORMANCE).

       BC_BASE_DIGS
	      Количество десятичных цифр на большое целое (см. раздел PERFORMANCE).  Зависит от BC_LONG_BIT.

       BC_BASE_POW
	      Максимальное десятичное число, которое каждое большое целое может хранить (см.
	      BC_BASE_DIGS) плюс 1.  Зависит от BC_BASE_DIGS.

       BC_OVERFLOW_MAX
	      Максимальное число, которое тип переполнения может удерживать (см. раздел PERFORMANCE).  Зависит от BC_LONG_BIT.

       BC_BASE_MAX
	      Максимальная выходная база.  Установлено на BC_BASE_POW.

       BC_DIM_MAX
	      Максимальный размер массивов.  Установлено на SIZE_MAX-1.

       BC_SCALE_MAX
	      Максимальный scale.  Установлено на BC_OVERFLOW_MAX-1.

       BC_STRING_MAX
	      Максимальная длина строк.  Установлено на BC_OVERFLOW_MAX-1.

       BC_NAME_MAX
	      Максимальная длина идентификаторов.  Установлено на BC_OVERFLOW_MAX-1.

       BC_NUM_MAX
	      Максимальная длина числа (в десятичных цифрах), которая включает
	      цифры после десятичной точки.  Установлено на BC_OVER‐
	      FLOW_MAX-1.

       BC_RAND_MAX
	      Максимальное целое (включительно), возвращаемое операндом rand().  Установлено на 2^BC_LONG_BIT-1.

       Показатель
	      Максимально допустимый показатель (положительный или отрицательный).  Установлено на
	      BC_OVERFLOW_MAX.

       Количество переменных
	      Максимальное количество переменных/массивов.  Установлено на SIZE_MAX-1.

       Фактические значения можно запросить с оператором limits.

       Эти ограничения предназначены для того, чтобы быть эффективно несуществующими; ограничения такие большие (как минимум на 64-битных машинах), что не должно быть никакого момента, в который они станут проблемой.  Фактически, память должна быть исчерпана перед тем, как эти ограничения будут достигнуты.

ENVIRONMENT VARIABLES
       Как нестандартные расширения, bc(1) распознает следующие переменные окружения:

       POSIXLY_CORRECT
	      Если эта переменная существует (независимо от содержимого), bc(1) ведет себя
	      так, как будто дана опция -s.

       BC_ENV_ARGS
	      Это еще один способ передать аргументы командной строки bc(1).
	      Они должны быть в том же формате, что и все другие аргументы командной строки.  Эти всегда обрабатываются первыми, так что любые файлы, данные в BC_ENV_ARGS, будут обработаны перед аргументами и файлами,
	      данными в командной строке.  Это дает пользователю возможность настроить "стандартные" опции и файлы для использования при каждом вызове.  Самое полезное для таких файлов - это полезные функции, которые пользователь может захотеть при каждом запуске bc(1).

	      Код, который парсит BC_ENV_ARGS, правильно обрабатывает quoted
	      аргументы, но не понимает последовательности escape.  Например, строка “/home/gavin/some bc file.bc” будет правильно разобрана, но строка “/home/gavin/some "bc" file.bc”
	      включит обратные слэши.

	      Парсинг кавычек будет обрабатывать любой вид кавычек, ' или “.
	      Таким образом, если у вас есть файл с любым количеством одинарных кавычек в имени, вы можете использовать двойные кавычки как внешние, как в
	      “some `bc' file.bc”, и наоборот, если у вас есть файл с двойными кавычками.  Однако, обработка файла с обоими видами кавычек в BC_ENV_ARGS не поддерживается из-за сложности парсинга, хотя такие файлы все еще поддерживаются в командной строке, где парсинг выполняется оболочкой.

       BC_LINE_LENGTH
	      Если эта переменная окружения существует и содержит целое, которое
	      больше 1 и меньше UINT16_MAX (2^16-1), bc(1) будет выводить строки этой длины, включая обратный слэш (\).
	      Длина строки по умолчанию - 70.

	      Специальное значение 0 отключит проверку длины строки
	      и напечатает числа без учета длины строки и без обратных
	      слэшей и новых строк.

       BC_BANNER
	      Если эта переменная окружения существует и содержит целое, то ненулевое значение активирует заголовок с авторскими правами, когда bc(1)
	      в интерактивном режиме, в то время как нуль деактивирует его.

	      Если bc(1) не в интерактивном режиме (см. раздел INTERACTIVE MODE),
	      то эта переменная окружения не имеет эффекта, потому что
	      bc(1) не печатает заголовок, когда не в интерактивном режиме.

	      Эта переменная окружения переопределяет значение по умолчанию, которое можно
	      запросить с опциями -h или --help.

       BC_SIGINT_RESET
	      Если bc(1) не в интерактивном режиме (см. раздел INTERACTIVE MODE),
	      то эта переменная окружения не имеет эффекта, потому что
	      bc(1) выходит на SIGINT, когда не в интерактивном режиме.

	      Однако, когда bc(1) в интерактивном режиме, то если эта переменная окружения существует и содержит целое, ненулевое значение заставляет bc(1) сбрасываться на SIGINT, а не выходить, и нуль заставляет bc(1) выйти.  Если эта переменная окружения существует и не является целым, то bc(1) выйдет на SIGINT.

	      Эта переменная окружения переопределяет значение по умолчанию, которое можно
	      запросить с опциями -h или --help.

       BC_TTY_MODE
	      Если режим TTY недоступен (см. раздел TTY MODE), то
	      эта переменная окружения не имеет эффекта.

	      Однако, когда режим TTY доступен, то если эта переменная окружения существует и содержит целое, то ненулевое значение заставляет bc(1) использовать режим TTY, и нуль заставляет bc(1) не использовать режим TTY.

	      Эта переменная окружения переопределяет значение по умолчанию, которое можно
	      запросить с опциями -h или --help.

       BC_PROMPT
	      Если режим TTY недоступен (см. раздел TTY MODE), то
	      эта переменная окружения не имеет эффекта.

	      Однако, когда режим TTY доступен, то если эта переменная окружения существует и содержит целое, ненулевое значение заставляет bc(1) использовать подсказку, и нуль или нецелое заставляет bc(1) не использовать подсказку.  Если эта переменная окружения не существует и BC_TTY_MODE существует, то используется значение переменной BC_TTY_MODE.

	      Эта переменная окружения и переменная BC_TTY_MODE переопределяют значение по умолчанию, которое можно
	      запросить с опциями -h или --help.

       BC_EXPR_EXIT
	      Если любые выражения или файлы выражений даны в командной строке с -e, --expression, -f или --file, то если эта переменная окружения существует и содержит целое, ненулевое значение заставляет bc(1) выйти после выполнения выражений и файлов выражений, и нулевое значение заставляет bc(1) не выходить.

	      Эта переменная окружения переопределяет значение по умолчанию, которое можно
	      запросить с опциями -h или --help.

       BC_DIGIT_CLAMP
	      При разборе чисел и если эта переменная окружения существует и содержит целое, ненулевое значение заставляет bc(1) ограничивать цифры, которые больше или равны текущему ibase, так что все такие цифры считаются равными ibase минус 1, и нулевое значение отключает такое ограничение, так что эти цифры всегда равны своему значению, которое умножается на степень ibase.

	      Это никогда не применяется к однозначным числам, как предписано стандартом
	      (см. раздел STANDARDS).

	      Эта переменная окружения переопределяет значение по умолчанию, которое можно
	      запросить с опциями -h или --help.

EXIT STATUS
       bc(1) возвращает следующие коды выхода:

       0      Нет ошибки.

       1      Произошла математическая ошибка.  Это следует стандартной практике использования
	      1 для ожидаемых ошибок, поскольку математические ошибки будут происходить в процессе нормального выполнения.

	      Математические ошибки включают деление на 0, извлечение квадратного корня из отрицательного числа, использование отрицательного числа как границы для генератора псевдослучайных чисел, попытку преобразовать отрицательное число в аппаратное целое, переполнение при преобразовании числа в аппаратное целое, переполнение при расчете размера числа и попытку использовать нецелое, где требуется целое.

	      Преобразование в аппаратное целое происходит для второго операнда
	      операторов возведения в степень (^), позиций (@), сдвига влево (<<) и сдвига вправо
	      (>>) и их соответствующих операторов присваивания.

       2      Произошла ошибка разбора.

	      Ошибки разбора включают неожиданный EOF, использование недопустимого символа,
	      неудачу в нахождении конца строки или комментария, использование токена, где он недопустим, предоставление недопустимого выражения, предоставление недопустимого оператора print, предоставление недопустимого определения функции,
	      попытку присвоить выражению, которое не является именованным выражением (см. подраздел Named Expressions раздела SYNTAX), предоставление недопустимого списка auto, наличие дублирующего auto/параметра функции, неудачу в нахождении конца блока кода, попытку вернуть значение из void функции, попытку использовать переменную как ссылку и использование любых расширений, когда опция -s или любые эквиваленты даны.

       3      Произошла ошибка времени выполнения.

	      Ошибки времени выполнения включают присваивание недопустимого числа любой глобальной
	      (ibase, obase или scale), предоставление плохого выражения вызову read(),
	      вызов read() внутри read(), ошибки типов, передачу неправильного количества аргументов функциям, попытку вызвать неопределенную функцию и попытку использовать вызов void функции как значение в выражении.

       4      Произошла фатальная ошибка.

	      Фатальные ошибки включают ошибки выделения памяти, ошибки I/O, неудачу в открытии файлов, попытку использовать файлы, которые не имеют только символов ASCII (bc(1) принимает только символы ASCII), попытку открыть каталог как файл и предоставление недопустимых опций командной строки.

       Код выхода 4 специальный; когда фатальная ошибка происходит, bc(1) всегда
       выходит и возвращает 4, независимо от режима, в котором bc(1) находится.

       Другие статусы будут возвращены только когда bc(1) не в интерактивном режиме (см. раздел INTERACTIVE MODE), поскольку bc(1) сбрасывает свое состояние (см. раздел RESET) и принимает больше ввода, когда одна из этих ошибок происходит в интерактивном режиме.  Это также верно, когда интерактивный режим принудительно включен флагом -i или опцией --interactive.

       Эти коды выхода позволяют использовать bc(1) в сценариях оболочки с проверкой ошибок, и его нормальное поведение может быть принудительно включено с помощью флага -i или опции --interactive.

INTERACTIVE MODE
       Согласно стандарту (см. раздел STANDARDS), bc(1) имеет интерактивный режим и неинтерактивный режим.  Интерактивный режим включается автоматически, когда stdin и stdout подключены к терминалу, но флаг -i и опция --interactive могут включить его в других ситуациях.

       В интерактивном режиме bc(1) пытается восстановиться от ошибок (см. раздел RE‐
       SET), и в нормальном выполнении, сбрасывает stdout как только выполнение завершено для текущего ввода.  bc(1) также может сбрасываться на SIGINT вместо выхода, в зависимости от содержимого или значения по умолчанию переменной окружения BC_SIGINT_RESET (см. раздел ENVIRONMENT VARIABLES).

TTY MODE
       Если stdin, stdout и stderr все подключены к TTY, то "TTY
       режим" считается доступным, и таким образом, bc(1) может включить TTY
       режим, с учетом некоторых настроек.

       Если существует переменная окружения BC_TTY_MODE в окружении
       (см. раздел ENVIRONMENT VARIABLES), то если эта переменная окружения содержит ненулевое целое, bc(1) включит TTY режим, когда stdin, stdout и stderr подключены к TTY.  Если переменная BC_TTY_MODE существует, но не является ненулевым целым, то bc(1) не включит TTY режим.

       Если переменная окружения BC_TTY_MODE не существует, используется значение по умолчанию.
       Значение по умолчанию можно запросить с опциями -h или --help.

       Режим TTY отличается от интерактивного режима, потому что интерактивный режим требуется в стандарте bc(1) (см. раздел STANDARDS), и интерактивный режим требует только stdin и stdout, подключенных к терминалу.

   Command-Line History
       История командной строки включается только если доступен режим TTY (см. раздел TTY MODE), история может быть включена.  Это означает, что историю командной строки можно включить только, когда stdin, stdout и stderr подключены к TTY.

       Как и сам режим TTY, его можно включить или выключить с переменной окружения BC_TTY_MODE (см. раздел ENVIRONMENT VARIABLES).

       Если история включена, предыдущие строки можно вспомнить и отредактировать со стрелочными клавишами.

       Примечание: табы преобразуются в 8 пробелов.

LOCALES
       Этот bc(1) поставляется с поддержкой добавления сообщений об ошибках для разных локалей и таким образом, поддерживает LC_MESSAGES.

SEE ALSO
       dc(1)

STANDARDS
       bc(1) соответствует спецификации IEEE Std 1003.1-2017 (“POSIX.1-2017”)
       по адресу https://pubs.opengroup.org/onlinepubs/9699919799/utili‐
       ties/bc.html .  Флаги -efghiqsvVw, все длинные опции и
       расширения, отмеченные выше, являются расширениями к этой спецификации.

       Кроме того, поведение quit реализует интерпретацию
       спецификации, которая отличается от всех известных реализаций.
       Для получения дополнительной информации см. подраздел Statements раздела SYNTAX.

       Обратите внимание, что спецификация явно говорит, что bc(1) принимает только числа, которые используют точку (.) как десятичную точку, независимо от значения LC_NUMERIC.

       Этот bc(1) поддерживает сообщения об ошибках для разных локалей, и таким образом, он
       поддерживает LC_MESSAGES.

BUGS
       До версии 6.1.0 этот bc(1) имел неправильное поведение для оператора quit.

       Другие ошибки не известны.  Сообщайте об ошибках по адресу https://git.gavin‐
       howard.com/gavin/bc .

AUTHORS
       Gavin D. Howard ⟨gavin@gavinhoward.com⟩ и contributors.
BC(1)			    General Commands Manual			 BC(1)



NAME
       bc - arbitrary-precision decimal arithmetic language and calculator

SYNOPSIS
       bc [-cCghilPqRsvVw] [--digit-clamp] [--no-digit-clamp]
       [--global-stacks] [--help] [--interactive] [--mathlib] [--no-prompt]
       [--no-read-prompt] [--quiet] [--standard] [--warn] [--version] [-e
       expr] [--expression=expr...]  [-f file...]  [--file=file...]  [file...]
       [-I ibase] [--ibase=ibase] [-O obase] [--obase=obase] [-S scale]
       [--scale=scale] [-E seed] [--seed=seed]

DESCRIPTION
       bc(1) is an interactive processor for a language first standardized in
       1991 by POSIX.  (See the STANDARDS section.)  The language provides
       unlimited precision decimal arithmetic and is somewhat C-like, but
       there are differences.  Such differences will be noted in this
       document.

       After parsing and handling options, this bc(1) reads any files given on
       the command line and executes them before reading from stdin.

       This bc(1) is a drop-in replacement for any bc(1), including (and
       especially) the GNU bc(1).  It also has many extensions and extra
       features beyond other implementations.

       Note: If running this bc(1) on any script meant for another bc(1) gives
       a parse error, it is probably because a word this bc(1) reserves as a
       keyword is used as the name of a function, variable, or array.  To fix
       that, use the command-line option -r keyword, where keyword is the
       keyword that is used as a name in the script.  For more information,
       see the OPTIONS section.

       If parsing scripts meant for other bc(1) implementations still does not
       work, that is a bug and should be reported.  See the BUGS section.

OPTIONS
       The following are the options that bc(1) accepts.

       -C, --no-digit-clamp
	      Disables clamping of digits greater than or equal to the current
	      ibase when parsing numbers.

	      This means that the value added to a number from a digit is
	      always that digit’s value multiplied by the value of ibase
	      raised to the power of the digit’s position, which starts from 0
	      at the least significant digit.

	      If this and/or the -c or --digit-clamp options are given
	      multiple times, the last one given is used.

	      This option overrides the BC_DIGIT_CLAMP environment variable
	      (see the ENVIRONMENT VARIABLES section) and the default, which
	      can be queried with the -h or --help options.

	      This is a non-portable extension.

       -c, --digit-clamp
	      Enables clamping of digits greater than or equal to the current
	      ibase when parsing numbers.

	      This means that digits that the value added to a number from a
	      digit that is greater than or equal to the ibase is the value of
	      ibase minus 1 all multiplied by the value of ibase raised to the
	      power of the digit’s position, which starts from 0 at the least
	      significant digit.

	      If this and/or the -C or --no-digit-clamp options are given
	      multiple times, the last one given is used.

	      This option overrides the BC_DIGIT_CLAMP environment variable
	      (see the ENVIRONMENT VARIABLES section) and the default, which
	      can be queried with the -h or --help options.

	      This is a non-portable extension.

       -E seed, --seed=seed
	      Sets the builtin variable seed to the value seed assuming that
	      seed is in base 10.  It is a fatal error if seed is not a valid
	      number.

	      If multiple instances of this option are given, the last is
	      used.

	      This is a non-portable extension.

       -e expr, --expression=expr
	      Evaluates expr.  If multiple expressions are given, they are
	      evaluated in order.  If files are given as well (see the -f and
	      --file options), the expressions and files are evaluated in the
	      order given.  This means that if a file is given before an
	      expression, the file is read in and evaluated first.

	      If this option is given on the command-line (i.e., not in
	      BC_ENV_ARGS, see the ENVIRONMENT VARIABLES section), then after
	      processing all expressions and files, bc(1) will exit, unless -
	      (stdin) was given as an argument at least once to -f or --file,
	      whether on the command-line or in BC_ENV_ARGS.  However, if any
	      other -e, --expression, -f, or --file arguments are given after
	      -f- or equivalent is given, bc(1) will give a fatal error and
	      exit.

	      This is a non-portable extension.

       -f file, --file=file
	      Reads in file and evaluates it, line by line, as though it were
	      read through stdin.  If expressions are also given (see the -e
	      and --expression options), the expressions are evaluated in the
	      order given.

	      If this option is given on the command-line (i.e., not in
	      BC_ENV_ARGS, see the ENVIRONMENT VARIABLES section), then after
	      processing all expressions and files, bc(1) will exit, unless -
	      (stdin) was given as an argument at least once to -f or --file.
	      However, if any other -e, --expression, -f, or --file arguments
	      are given after -f- or equivalent is given, bc(1) will give a
	      fatal error and exit.

	      This is a non-portable extension.

       -g, --global-stacks
	      Turns the globals ibase, obase, scale, and seed into stacks.

	      This has the effect that a copy of the current value of all four
	      are pushed onto a stack for every function call, as well as
	      popped when every function returns.  This means that functions
	      can assign to any and all of those globals without worrying that
	      the change will affect other functions.  Thus, a hypothetical
	      function named output(x,b) that simply printed x in base b could
	      be written like this:

		     define void output(x, b) {
			 obase=b
			 x
		     }

	      instead of like this:

		     define void output(x, b) {
			 auto c
			 c=obase
			 obase=b
			 x
			 obase=c
		     }

	      This makes writing functions much easier.

	      (Note: the function output(x,b) exists in the extended math li‐
	      brary.  See the LIBRARY section.)

	      However, since using this flag means that functions cannot set
	      ibase, obase, scale, or seed globally, functions that are made
	      to do so cannot work anymore.  There are two possible use cases
	      for that, and each has a solution.

	      First, if a function is called on startup to turn bc(1) into a
	      number converter, it is possible to replace that capability with
	      various shell aliases.  Examples:

		     alias d2o="bc -e ibase=A -e obase=8"
		     alias h2b="bc -e ibase=G -e obase=2"

	      Second, if the purpose of a function is to set ibase, obase,
	      scale, or seed globally for any other purpose, it could be split
	      into one to four functions (based on how many globals it sets)
	      and each of those functions could return the desired value for a
	      global.

	      For functions that set seed, the value assigned to seed is not
	      propagated to parent functions.  This means that the sequence of
	      pseudo-random numbers that they see will not be the same se‐
	      quence of pseudo-random numbers that any parent sees.  This is
	      only the case once seed has been set.

	      If a function desires to not affect the sequence of pseudo-ran‐
	      dom numbers of its parents, but wants to use the same seed, it
	      can use the following line:

		     seed = seed

	      If the behavior of this option is desired for every run of
	      bc(1), then users could make sure to define BC_ENV_ARGS and in‐
	      clude this option (see the ENVIRONMENT VARIABLES section for
	      more details).

	      If -s, -w, or any equivalents are used, this option is ignored.

	      This is a non-portable extension.

       -h, --help
	      Prints a usage message and exits.

       -I ibase, --ibase=ibase
	      Sets the builtin variable ibase to the value ibase assuming that
	      ibase is in base 10.  It is a fatal error if ibase is not a
	      valid number.

	      If multiple instances of this option are given, the last is
	      used.

	      This is a non-portable extension.

       -i, --interactive
	      Forces interactive mode.	(See the INTERACTIVE MODE section.)

	      This is a non-portable extension.

       -L, --no-line-length
	      Disables line length checking and prints numbers without back‐
	      slashes and newlines.  In other words, this option sets
	      BC_LINE_LENGTH to 0 (see the ENVIRONMENT VARIABLES section).

	      This is a non-portable extension.

       -l, --mathlib
	      Sets scale (see the SYNTAX section) to 20 and loads the included
	      math library and the extended math library before running any
	      code, including any expressions or files specified on the com‐
	      mand line.

	      To learn what is in the libraries, see the LIBRARY section.

       -O obase, --obase=obase
	      Sets the builtin variable obase to the value obase assuming that
	      obase is in base 10.  It is a fatal error if obase is not a
	      valid number.

	      If multiple instances of this option are given, the last is
	      used.

	      This is a non-portable extension.

       -P, --no-prompt
	      Disables the prompt in TTY mode.	(The prompt is only enabled in
	      TTY mode.	 See the TTY MODE section.)  This is mostly for those
	      users that do not want a prompt or are not used to having them
	      in bc(1).	 Most of those users would want to put this option in
	      BC_ENV_ARGS (see the ENVIRONMENT VARIABLES section).

	      These options override the BC_PROMPT and BC_TTY_MODE environment
	      variables (see the ENVIRONMENT VARIABLES section).

	      This is a non-portable extension.

       -q, --quiet
	      This option is for compatibility with the GNU bc(1)
	      (https://www.gnu.org/software/bc/); it is a no-op.  Without this
	      option, GNU bc(1) prints a copyright header.  This bc(1) only
	      prints the copyright header if one or more of the -v, -V, or
	      --version options are given unless the BC_BANNER environment
	      variable is set and contains a non-zero integer or if this bc(1)
	      was built with the header displayed by default.  If any of that
	      is the case, then this option does prevent bc(1) from printing
	      the header.

	      This is a non-portable extension.

       -R, --no-read-prompt
	      Disables the read prompt in TTY mode.  (The read prompt is only
	      enabled in TTY mode.  See the TTY MODE section.)	This is mostly
	      for those users that do not want a read prompt or are not used
	      to having them in bc(1).	Most of those users would want to put
	      this option in BC_ENV_ARGS (see the ENVIRONMENT VARIABLES sec‐
	      tion).  This option is also useful in hash bang lines of bc(1)
	      scripts that prompt for user input.

	      This option does not disable the regular prompt because the read
	      prompt is only used when the read() built-in function is called.

	      These options do override the BC_PROMPT and BC_TTY_MODE environ‐
	      ment variables (see the ENVIRONMENT VARIABLES section), but only
	      for the read prompt.

	      This is a non-portable extension.

       -r keyword, --redefine=keyword
	      Redefines keyword in order to allow it to be used as a function,
	      variable, or array name.	This is useful when this bc(1) gives
	      parse errors when parsing scripts meant for other bc(1) imple‐
	      mentations.

	      The keywords this bc(1) allows to be redefined are:

	      • abs

	      • asciify

	      • continue

	      • divmod

	      • else

	      • halt

	      • irand

	      • last

	      • limits

	      • maxibase

	      • maxobase

	      • maxrand

	      • maxscale

	      • modexp

	      • print

	      • rand

	      • read

	      • seed

	      • stream

	      If any of those keywords are used as a function, variable, or
	      array name in a script, use this option with the keyword as the
	      argument.	 If multiple are used, use this option for all of
	      them; it can be used multiple times.

	      Keywords are not redefined when parsing the builtin math library
	      (see the LIBRARY section).

	      It is a fatal error to redefine keywords mandated by the POSIX
	      standard (see the STANDARDS section).  It is a fatal error to
	      attempt to redefine words that this bc(1) does not reserve as
	      keywords.

       -S scale, --scale=scale
	      Sets the builtin variable scale to the value scale assuming that
	      scale is in base 10.  It is a fatal error if scale is not a
	      valid number.

	      If multiple instances of this option are given, the last is
	      used.

	      This is a non-portable extension.

       -s, --standard
	      Process exactly the language defined by the standard (see the
	      STANDARDS section) and error if any extensions are used.

	      This is a non-portable extension.

       -v, -V, --version
	      Print the version information (copyright header) and exits.

	      This is a non-portable extension.

       -w, --warn
	      Like -s and --standard, except that warnings (and not errors)
	      are printed for non-standard extensions and execution continues
	      normally.

	      This is a non-portable extension.

       -z, --leading-zeroes
	      Makes bc(1) print all numbers greater than -1 and less than 1,
	      and not equal to 0, with a leading zero.

	      This can be set for individual numbers with the plz(x),
	      plznl(x), pnlz(x), and pnlznl(x) functions in the extended math
	      library (see the LIBRARY section).

	      This is a non-portable extension.

       All long options are non-portable extensions.

STDIN
       If no files or expressions are given by the -f, --file, -e, or --ex‐
       pression options, then bc(1) reads from stdin.

       However, there are a few caveats to this.

       First, stdin is evaluated a line at a time.  The only exception to this
       is if the parse cannot complete.	 That means that starting a string
       without ending it or starting a function, if statement, or loop without
       ending it will also cause bc(1) to not execute.

       Second, after an if statement, bc(1) doesn’t know if an else statement
       will follow, so it will not execute until it knows there will not be an
       else statement.

STDOUT
       Any non-error output is written to stdout.  In addition, if history
       (see the HISTORY section) and the prompt (see the TTY MODE section) are
       enabled, both are output to stdout.

       Note: Unlike other bc(1) implementations, this bc(1) will issue a fatal
       error (see the EXIT STATUS section) if it cannot write to stdout, so if
       stdout is closed, as in bc  >&-, it will quit with an error.  This is
       done so that bc(1) can report problems when stdout is redirected to a
       file.

       If there are scripts that depend on the behavior of other bc(1) imple‐
       mentations, it is recommended that those scripts be changed to redirect
       stdout to /dev/null.

STDERR
       Any error output is written to stderr.

       Note: Unlike other bc(1) implementations, this bc(1) will issue a fatal
       error (see the EXIT STATUS section) if it cannot write to stderr, so if
       stderr is closed, as in bc  2>&-, it will quit with an error.  This is
       done so that bc(1) can exit with an error code when stderr is redi‐
       rected to a file.

       If there are scripts that depend on the behavior of other bc(1) imple‐
       mentations, it is recommended that those scripts be changed to redirect
       stderr to /dev/null.

SYNTAX
       The syntax for bc(1) programs is mostly C-like, with some differences.
       This bc(1) follows the POSIX standard (see the STANDARDS section),
       which is a much more thorough resource for the language this bc(1) ac‐
       cepts.  This section is meant to be a summary and a listing of all the
       extensions to the standard.

       In the sections below, E means expression, S means statement, and I
       means identifier.

       Identifiers (I) start with a lowercase letter and can be followed by
       any number (up to BC_NAME_MAX-1) of lowercase letters (a-z), digits
       (0-9), and underscores (_).  The regex is [a-z][a-z0-9_]*.  Identifiers
       with more than one character (letter) are a non-portable extension.

       ibase is a global variable determining how to interpret constant num‐
       bers.  It is the “input” base, or the number base used for interpreting
       input numbers.  ibase is initially 10.  If the -s (--standard) and -w
       (--warn) flags were not given on the command line, the max allowable
       value for ibase is 36.  Otherwise, it is 16.  The min allowable value
       for ibase is 2.	The max allowable value for ibase can be queried in
       bc(1) programs with the maxibase() built-in function.

       obase is a global variable determining how to output results.  It is
       the “output” base, or the number base used for outputting numbers.
       obase is initially 10.  The max allowable value for obase is
       BC_BASE_MAX and can be queried in bc(1) programs with the maxobase()
       built-in function.  The min allowable value for obase is 0.  If obase
       is 0, values are output in scientific notation, and if obase is 1, val‐
       ues are output in engineering notation.	Otherwise, values are output
       in the specified base.

       Outputting in scientific and engineering notations are non-portable ex‐
       tensions.

       The scale of an expression is the number of digits in the result of the
       expression right of the decimal point, and scale is a global variable
       that sets the precision of any operations, with exceptions.  scale is
       initially 0.  scale cannot be negative.	The max allowable value for
       scale is BC_SCALE_MAX and can be queried in bc(1) programs with the
       maxscale() built-in function.

       bc(1) has both global variables and local variables.  All local vari‐
       ables are local to the function; they are parameters or are introduced
       in the auto list of a function (see the FUNCTIONS section).  If a vari‐
       able is accessed which is not a parameter or in the auto list, it is
       assumed to be global.  If a parent function has a local variable ver‐
       sion of a variable that a child function considers global, the value of
       that global variable in the child function is the value of the variable
       in the parent function, not the value of the actual global variable.

       All of the above applies to arrays as well.

       The value of a statement that is an expression (i.e., any of the named
       expressions or operands) is printed unless the lowest precedence opera‐
       tor is an assignment operator and the expression is notsurrounded by
       parentheses.

       The value that is printed is also assigned to the special variable
       last.  A single dot (.) may also be used as a synonym for last.	These
       are non-portable extensions.

       Either semicolons or newlines may separate statements.

   Comments
       There are two kinds of comments:

       1. Block comments are enclosed in /* and */.

       2. Line comments go from # until, and not including, the next newline.
	  This is a non-portable extension.

   Named Expressions
       The following are named expressions in bc(1):

       1. Variables: I

       2. Array Elements: I[E]

       3. ibase

       4. obase

       5. scale

       6. seed

       7. last or a single dot (.)

       Numbers 6 and 7 are non-portable extensions.

       The meaning of seed is dependent on the current pseudo-random number
       generator but is guaranteed to not change except for new major ver‐
       sions.

       The scale and sign of the value may be significant.

       If a previously used seed value is assigned to seed and used again, the
       pseudo-random number generator is guaranteed to produce the same se‐
       quence of pseudo-random numbers as it did when the seed value was pre‐
       viously used.

       The exact value assigned to seed is not guaranteed to be returned if
       seed is queried again immediately.  However, if seed does return a dif‐
       ferent value, both values, when assigned to seed, are guaranteed to
       produce the same sequence of pseudo-random numbers.  This means that
       certain values assigned to seed will not produce unique sequences of
       pseudo-random numbers.  The value of seed will change after any use of
       the rand() and irand(E) operands (see the Operands subsection below),
       except if the parameter passed to irand(E) is 0, 1, or negative.

       There is no limit to the length (number of significant decimal digits)
       or scale of the value that can be assigned to seed.

       Variables and arrays do not interfere; users can have arrays named the
       same as variables.  This also applies to functions (see the FUNCTIONS
       section), so a user can have a variable, array, and function that all
       have the same name, and they will not shadow each other, whether inside
       of functions or not.

       Named expressions are required as the operand of increment/decrement
       operators and as the left side of assignment operators (see the Opera‐
       tors subsection).

   Operands
       The following are valid operands in bc(1):

	1. Numbers (see the Numbers subsection below).

	2. Array indices (I[E]).

	3. (E): The value of E (used to change precedence).

	4. sqrt(E): The square root of E.  E must be non-negative.

	5. length(E): The number of significant decimal digits in E.  Returns
	   1 for 0 with no decimal places.  If given a string, the length of
	   the string is returned.  Passing a string to length(E) is a
	   non-portable extension.

	6. length(I[]): The number of elements in the array I.	This is a
	   non-portable extension.

	7. scale(E): The scale of E.

	8. abs(E): The absolute value of E.  This is a non-portable extension.

	9. is_number(E): 1 if the given argument is a number, 0 if it is a
	   string.  This is a non-portable extension.

       10. is_string(E): 1 if the given argument is a string, 0 if it is a
	   number.  This is a non-portable extension.

       11. modexp(E, E, E): Modular exponentiation, where the first expression
	   is the base, the second is the exponent, and the third is the modu‐
	   lus.	 All three values must be integers.  The second argument must
	   be non-negative.  The third argument must be non-zero.  This is a
	   non-portable extension.

       12. divmod(E, E, I[]): Division and modulus in one operation.  This is
	   for optimization.  The first expression is the dividend, and the
	   second is the divisor, which must be non-zero.  The return value is
	   the quotient, and the modulus is stored in index 0 of the provided
	   array (the last argument).  This is a non-portable extension.

       13. asciify(E): If E is a string, returns a string that is the first
	   letter of its argument.  If it is a number, calculates the number
	   mod 256 and returns that number as a one-character string.  This is
	   a non-portable extension.

       14. asciify(I[]): A string that is made up of the characters that would
	   result from running asciify(E) on each element of the array identi‐
	   fied by the argument.  This allows creating multi-character strings
	   and storing them.  This is a non-portable extension.

       15. I(), I(E), I(E, E), and so on, where I is an identifier for a
	   non-void function (see the Void Functions subsection of the FUNC‐
	   TIONS section).  The E argument(s) may also be arrays of the form
	   I[], which will automatically be turned into array references (see
	   the Array References subsection of the FUNCTIONS section) if the
	   corresponding parameter in the function definition is an array ref‐
	   erence.

       16. read(): Reads a line from stdin and uses that as an expression.
	   The result of that expression is the result of the read() operand.
	   This is a non-portable extension.

       17. maxibase(): The max allowable ibase.	 This is a non-portable exten‐
	   sion.

       18. maxobase(): The max allowable obase.	 This is a non-portable exten‐
	   sion.

       19. maxscale(): The max allowable scale.	 This is a non-portable exten‐
	   sion.

       20. line_length(): The line length set with BC_LINE_LENGTH (see the EN‐
	   VIRONMENT VARIABLES section).  This is a non-portable extension.

       21. global_stacks(): 0 if global stacks are not enabled with the -g or
	   --global-stacks options, non-zero otherwise.	 See the OPTIONS sec‐
	   tion.  This is a non-portable extension.

       22. leading_zero(): 0 if leading zeroes are not enabled with the -z or
	   –leading-zeroes options, non-zero otherwise.	 See the OPTIONS sec‐
	   tion.  This is a non-portable extension.

       23. rand(): A pseudo-random integer between 0 (inclusive) and
	   BC_RAND_MAX (inclusive).  Using this operand will change the value
	   of seed.  This is a non-portable extension.

       24. irand(E): A pseudo-random integer between 0 (inclusive) and the
	   value of E (exclusive).  If E is negative or is a non-integer (E’s
	   scale is not 0), an error is raised, and bc(1) resets (see the RE‐
	   SET section) while seed remains unchanged.  If E is larger than
	   BC_RAND_MAX, the higher bound is honored by generating several
	   pseudo-random integers, multiplying them by appropriate powers of
	   BC_RAND_MAX+1, and adding them together.  Thus, the size of integer
	   that can be generated with this operand is unbounded.  Using this
	   operand will change the value of seed, unless the value of E is 0
	   or 1.  In that case, 0 is returned, and seed is not changed.	 This
	   is a non-portable extension.

       25. maxrand(): The max integer returned by rand().  This is a non-por‐
	   table extension.

       The integers generated by rand() and irand(E) are guaranteed to be as
       unbiased as possible, subject to the limitations of the pseudo-random
       number generator.

       Note: The values returned by the pseudo-random number generator with
       rand() and irand(E) are guaranteed to NOT be cryptographically secure.
       This is a consequence of using a seeded pseudo-random number generator.
       However, they are guaranteed to be reproducible with identical seed
       values.	This means that the pseudo-random values from bc(1) should
       only be used where a reproducible stream of pseudo-random numbers is
       ESSENTIAL.  In any other case, use a non-seeded pseudo-random number
       generator.

   Numbers
       Numbers are strings made up of digits, uppercase letters, and at most 1
       period for a radix.  Numbers can have up to BC_NUM_MAX digits.  Upper‐
       case letters are equal to 9 plus their position in the alphabet, start‐
       ing from 1 (i.e., A equals 10, or 9+1).

       If a digit or letter makes no sense with the current value of ibase
       (i.e., they are greater than or equal to the current value of ibase),
       then the behavior depends on the existence of the -c/--digit-clamp or
       -C/--no-digit-clamp options (see the OPTIONS section), the existence
       and setting of the BC_DIGIT_CLAMP environment variable (see the ENVI‐
       RONMENT VARIABLES section), or the default, which can be queried with
       the -h/--help option.

       If clamping is off, then digits or letters that are greater than or
       equal to the current value of ibase are not changed.  Instead, their
       given value is multiplied by the appropriate power of ibase and added
       into the number.	 This means that, with an ibase of 3, the number AB is
       equal to 3^1*A+3^0*B, which is 3 times 10 plus 11, or 41.

       If clamping is on, then digits or letters that are greater than or
       equal to the current value of ibase are set to the value of the highest
       valid digit in ibase before being multiplied by the appropriate power
       of ibase and added into the number.  This means that, with an ibase of
       3, the number AB is equal to 3^1*2+3^0*2, which is 3 times 2 plus 2, or
       8.

       There is one exception to clamping: single-character numbers (i.e., A
       alone).	Such numbers are never clamped and always take the value they
       would have in the highest possible ibase.  This means that A alone al‐
       ways equals decimal 10 and Z alone always equals decimal 35.  This be‐
       havior is mandated by the standard (see the STANDARDS section) and is
       meant to provide an easy way to set the current ibase (with the i com‐
       mand) regardless of the current value of ibase.

       If clamping is on, and the clamped value of a character is needed, use
       a leading zero, i.e., for A, use 0A.

       In addition, bc(1) accepts numbers in scientific notation.  These have
       the form <number>e<integer>.  The exponent (the portion after the e)
       must be an integer.  An example is 1.89237e9, which is equal to
       1892370000.  Negative exponents are also allowed, so 4.2890e-3 is equal
       to 0.0042890.

       Using scientific notation is an error or warning if the -s or -w, re‐
       spectively, command-line options (or equivalents) are given.

       WARNING: Both the number and the exponent in scientific notation are
       interpreted according to the current ibase, but the number is still
       multiplied by 10^exponent regardless of the current ibase.  For exam‐
       ple, if ibase is 16 and bc(1) is given the number string FFeA, the re‐
       sulting decimal number will be 2550000000000, and if bc(1) is given the
       number string 10e-4, the resulting decimal number will be 0.0016.

       Accepting input as scientific notation is a non-portable extension.

   Operators
       The following arithmetic and logical operators can be used.  They are
       listed in order of decreasing precedence.  Operators in the same group
       have the same precedence.

       ++ --  Type: Prefix and Postfix

	      Associativity: None

	      Description: increment, decrement

       - !    Type: Prefix

	      Associativity: None

	      Description: negation, boolean not

       $      Type: Postfix

	      Associativity: None

	      Description: truncation

       @      Type: Binary

	      Associativity: Right

	      Description: set precision

       ^      Type: Binary

	      Associativity: Right

	      Description: power

       * / %  Type: Binary

	      Associativity: Left

	      Description: multiply, divide, modulus

       + -    Type: Binary

	      Associativity: Left

	      Description: add, subtract

       << >>  Type: Binary

	      Associativity: Left

	      Description: shift left, shift right

       = <<= >>= += -= *= /= %= ^= @=
	      Type: Binary

	      Associativity: Right

	      Description: assignment

       == <= >= != < >
	      Type: Binary

	      Associativity: Left

	      Description: relational

       &&     Type: Binary

	      Associativity: Left

	      Description: boolean and

       ||     Type: Binary

	      Associativity: Left

	      Description: boolean or

       The operators will be described in more detail below.

       ++ --  The prefix and postfix increment and decrement operators behave
	      exactly like they would in C. They require a named expression
	      (see the Named Expressions subsection) as an operand.

	      The prefix versions of these operators are more efficient; use
	      them where possible.

       -      The negation operator returns 0 if a user attempts to negate any
	      expression with the value 0.  Otherwise, a copy of the expres‐
	      sion with its sign flipped is returned.

       !      The boolean not operator returns 1 if the expression is 0, or 0
	      otherwise.

	      Warning: This operator has a different precedence than the
	      equivalent operator in GNU bc(1) and other bc(1) implementa‐
	      tions!

	      This is a non-portable extension.

       $      The truncation operator returns a copy of the given expression
	      with all of its scale removed.

	      This is a non-portable extension.

       @      The set precision operator takes two expressions and returns a
	      copy of the first with its scale equal to the value of the sec‐
	      ond expression.  That could either mean that the number is re‐
	      turned without change (if the scale of the first expression
	      matches the value of the second expression), extended (if it is
	      less), or truncated (if it is more).

	      The second expression must be an integer (no scale) and non-neg‐
	      ative.

	      This is a non-portable extension.

       ^      The power operator (not the exclusive or operator, as it would
	      be in C) takes two expressions and raises the first to the power
	      of the value of the second.  The scale of the result is equal to
	      scale.

	      The second expression must be an integer (no scale), and if it
	      is negative, the first value must be non-zero.

       *      The multiply operator takes two expressions, multiplies them,
	      and returns the product.	If a is the scale of the first expres‐
	      sion and b is the scale of the second expression, the scale of
	      the result is equal to min(a+b,max(scale,a,b)) where min() and
	      max() return the obvious values.

       /      The divide operator takes two expressions, divides them, and re‐
	      turns the quotient.  The scale of the result shall be the value
	      of scale.

	      The second expression must be non-zero.

       %      The modulus operator takes two expressions, a and b, and evalu‐
	      ates them by 1) Computing a/b to current scale and 2) Using the
	      result of step 1 to calculate a-(a/b)*b to scale
	      max(scale+scale(b),scale(a)).

	      The second expression must be non-zero.

       +      The add operator takes two expressions, a and b, and returns the
	      sum, with a scale equal to the max of the scales of a and b.

       -      The subtract operator takes two expressions, a and b, and re‐
	      turns the difference, with a scale equal to the max of the
	      scales of a and b.

       <<     The left shift operator takes two expressions, a and b, and re‐
	      turns a copy of the value of a with its decimal point moved b
	      places to the right.

	      The second expression must be an integer (no scale) and non-neg‐
	      ative.

	      This is a non-portable extension.

       >>     The right shift operator takes two expressions, a and b, and re‐
	      turns a copy of the value of a with its decimal point moved b
	      places to the left.

	      The second expression must be an integer (no scale) and non-neg‐
	      ative.

	      This is a non-portable extension.

       = <<= >>= += -= *= /= %= ^= @=
	      The assignment operators take two expressions, a and b where a
	      is a named expression (see the Named Expressions subsection).

	      For =, b is copied and the result is assigned to a.  For all
	      others, a and b are applied as operands to the corresponding
	      arithmetic operator and the result is assigned to a.

	      The assignment operators that correspond to operators that are
	      extensions are themselves non-portable extensions.

       == <= >= != < >
	      The relational operators compare two expressions, a and b, and
	      if the relation holds, according to C language semantics, the
	      result is 1.  Otherwise, it is 0.

	      Note that unlike in C, these operators have a lower precedence
	      than the assignment operators, which means that a=b>c is inter‐
	      preted as (a=b)>c.

	      Also, unlike the standard (see the STANDARDS section) requires,
	      these operators can appear anywhere any other expressions can be
	      used.  This allowance is a non-portable extension.

       &&     The boolean and operator takes two expressions and returns 1 if
	      both expressions are non-zero, 0 otherwise.

	      This is not a short-circuit operator.

	      This is a non-portable extension.

       ||     The boolean or operator takes two expressions and returns 1 if
	      one of the expressions is non-zero, 0 otherwise.

	      This is not a short-circuit operator.

	      This is a non-portable extension.

   Statements
       The following items are statements:

	1. E

	2. { S ; ...  ; S }

	3. if ( E ) S

	4. if ( E ) S else S

	5. while ( E ) S

	6. for ( E ; E ; E ) S

	7. An empty statement

	8. break

	9. continue

       10. quit

       11. halt

       12. limits

       13. A string of characters, enclosed in double quotes

       14. print E , ...  , E

       15. stream E , ...  , E

       16. I(), I(E), I(E, E), and so on, where I is an identifier for a void
	   function (see the Void Functions subsection of the FUNCTIONS sec‐
	   tion).  The E argument(s) may also be arrays of the form I[], which
	   will automatically be turned into array references (see the Array
	   References subsection of the FUNCTIONS section) if the correspond‐
	   ing parameter in the function definition is an array reference.

       Numbers 4, 9, 11, 12, 14, 15, and 16 are non-portable extensions.

       Also, as a non-portable extension, any or all of the expressions in the
       header of a for loop may be omitted.  If the condition (second expres‐
       sion) is omitted, it is assumed to be a constant 1.

       The break statement causes a loop to stop iterating and resume execu‐
       tion immediately following a loop.  This is only allowed in loops.

       The continue statement causes a loop iteration to stop early and re‐
       turns to the start of the loop, including testing the loop condition.
       This is only allowed in loops.

       The if else statement does the same thing as in C.

       The quit statement causes bc(1) to quit, even if it is on a branch that
       will not be executed (it is a compile-time command).

       Warning: The behavior of this bc(1) on quit is slightly different from
       other bc(1) implementations.  Other bc(1) implementations will exit as
       soon as they finish parsing the line that a quit command is on.	This
       bc(1) will execute any completed and executable statements that occur
       before the quit statement before exiting.

       In other words, for the bc(1) code below:

	      for (i = 0; i < 3; ++i) i; quit

       Other bc(1) implementations will print nothing, and this bc(1) will
       print 0, 1, and 2 on successive lines before exiting.

       The halt statement causes bc(1) to quit, if it is executed.  (Unlike
       quit if it is on a branch of an if statement that is not executed,
       bc(1) does not quit.)

       The limits statement prints the limits that this bc(1) is subject to.
       This is like the quit statement in that it is a compile-time command.

       An expression by itself is evaluated and printed, followed by a new‐
       line.

       Both scientific notation and engineering notation are available for
       printing the results of expressions.  Scientific notation is activated
       by assigning 0 to obase, and engineering notation is activated by as‐
       signing 1 to obase.  To deactivate them, just assign a different value
       to obase.

       Scientific notation and engineering notation are disabled if bc(1) is
       run with either the -s or -w command-line options (or equivalents).

       Printing numbers in scientific notation and/or engineering notation is
       a non-portable extension.

   Strings
       If strings appear as a statement by themselves, they are printed with‐
       out a trailing newline.

       In addition to appearing as a lone statement by themselves, strings can
       be assigned to variables and array elements.  They can also be passed
       to functions in variable parameters.

       If any statement that expects a string is given a variable that had a
       string assigned to it, the statement acts as though it had received a
       string.

       If any math operation is attempted on a string or a variable or array
       element that has been assigned a string, an error is raised, and bc(1)
       resets (see the RESET section).

       Assigning strings to variables and array elements and passing them to
       functions are non-portable extensions.

   Print Statement
       The “expressions” in a print statement may also be strings.  If they
       are, there are backslash escape sequences that are interpreted spe‐
       cially.	What those sequences are, and what they cause to be printed,
       are shown below:

       \a: \a

       \b: \b

       \\: \

       \e: \

       \f: \f

       \n: \n

       \q: “

       \r: \r

       \t: \t

       Any other character following a backslash causes the backslash and
       character to be printed as-is.

       Any non-string expression in a print statement shall be assigned to
       last, like any other expression that is printed.

   Stream Statement
       The expressions in a stream statement may also be strings.

       If a stream statement is given a string, it prints the string as though
       the string had appeared as its own statement.  In other words, the
       stream statement prints strings normally, without a newline.

       If a stream statement is given a number, a copy of it is truncated and
       its absolute value is calculated.  The result is then printed as though
       obase is 256 and each digit is interpreted as an 8-bit ASCII character,
       making it a byte stream.

   Order of Evaluation
       All expressions in a statment are evaluated left to right, except as
       necessary to maintain order of operations.  This means, for example,
       assuming that i is equal to 0, in the expression

	      a[i++] = i++

       the first (or 0th) element of a is set to 1, and i is equal to 2 at the
       end of the expression.

       This includes function arguments.  Thus, assuming i is equal to 0, this
       means that in the expression

	      x(i++, i++)

       the first argument passed to x() is 0, and the second argument is 1,
       while i is equal to 2 before the function starts executing.

FUNCTIONS
       Function definitions are as follows:

	      define I(I,...,I){
		  auto I,...,I
		  S;...;S
		  return(E)
	      }

       Any I in the parameter list or auto list may be replaced with I[] to
       make a parameter or auto var an array, and any I in the parameter list
       may be replaced with *I[] to make a parameter an array reference.
       Callers of functions that take array references should not put an as‐
       terisk in the call; they must be called with just I[] like normal array
       parameters and will be automatically converted into references.

       As a non-portable extension, the opening brace of a define statement
       may appear on the next line.

       As a non-portable extension, the return statement may also be in one of
       the following forms:

       1. return

       2. return ( )

       3. return E

       The first two, or not specifying a return statement, is equivalent to
       return (0), unless the function is a void function (see the Void Func‐
       tions subsection below).

   Void Functions
       Functions can also be void functions, defined as follows:

	      define void I(I,...,I){
		  auto I,...,I
		  S;...;S
		  return
	      }

       They can only be used as standalone expressions, where such an expres‐
       sion would be printed alone, except in a print statement.

       Void functions can only use the first two return statements listed
       above.  They can also omit the return statement entirely.

       The word “void” is not treated as a keyword; it is still possible to
       have variables, arrays, and functions named void.  The word “void” is
       only treated specially right after the define keyword.

       This is a non-portable extension.

   Array References
       For any array in the parameter list, if the array is declared in the
       form

	      *I[]

       it is a reference.  Any changes to the array in the function are re‐
       flected, when the function returns, to the array that was passed in.

       Other than this, all function arguments are passed by value.

       This is a non-portable extension.

LIBRARY
       All of the functions below, including the functions in the extended
       math library (see the Extended Library subsection below), are available
       when the -l or --mathlib command-line flags are given, except that the
       extended math library is not available when the -s option, the -w op‐
       tion, or equivalents are given.

   Standard Library
       The standard (see the STANDARDS section) defines the following func‐
       tions for the math library:

       s(x)   Returns the sine of x, which is assumed to be in radians.

	      This is a transcendental function (see the Transcendental Func‐
	      tions subsection below).

       c(x)   Returns the cosine of x, which is assumed to be in radians.

	      This is a transcendental function (see the Transcendental Func‐
	      tions subsection below).

       a(x)   Returns the arctangent of x, in radians.

	      This is a transcendental function (see the Transcendental Func‐
	      tions subsection below).

       l(x)   Returns the natural logarithm of x.

	      This is a transcendental function (see the Transcendental Func‐
	      tions subsection below).

       e(x)   Returns the mathematical constant e raised to the power of x.

	      This is a transcendental function (see the Transcendental Func‐
	      tions subsection below).

       j(x, n)
	      Returns the bessel integer order n (truncated) of x.

	      This is a transcendental function (see the Transcendental Func‐
	      tions subsection below).

   Extended Library
       The extended library is not loaded when the -s/--standard or -w/--warn
       options are given since they are not part of the library defined by the
       standard (see the STANDARDS section).

       The extended library is a non-portable extension.

       p(x, y)
	      Calculates x to the power of y, even if y is not an integer, and
	      returns the result to the current scale.

	      It is an error if y is negative and x is 0.

	      This is a transcendental function (see the Transcendental Func‐
	      tions subsection below).

       r(x, p)
	      Returns x rounded to p decimal places according to the rounding
	      mode round half away from 0
	      (https://en.wikipedia.org/wiki/Round‐
	      ing#Round_half_away_from_zero).

       ceil(x, p)
	      Returns x rounded to p decimal places according to the rounding
	      mode round away from 0 (https://en.wikipedia.org/wiki/Round‐
	      ing#Rounding_away_from_zero).

       f(x)   Returns the factorial of the truncated absolute value of x.

       max(a, b)
	      Returns a if a is greater than b; otherwise, returns b.

       min(a, b)
	      Returns a if a is less than b; otherwise, returns b.

       perm(n, k)
	      Returns the permutation of the truncated absolute value of n of
	      the truncated absolute value of k, if k <= n.  If not, it re‐
	      turns 0.

       comb(n, k)
	      Returns the combination of the truncated absolute value of n of
	      the truncated absolute value of k, if k <= n.  If not, it re‐
	      turns 0.

       fib(n) Returns the Fibonacci number of the truncated absolute value of
	      n.

       l2(x)  Returns the logarithm base 2 of x.

	      This is a transcendental function (see the Transcendental Func‐
	      tions subsection below).

       l10(x) Returns the logarithm base 10 of x.

	      This is a transcendental function (see the Transcendental Func‐
	      tions subsection below).

       log(x, b)
	      Returns the logarithm base b of x.

	      This is a transcendental function (see the Transcendental Func‐
	      tions subsection below).

       cbrt(x)
	      Returns the cube root of x.

       root(x, n)
	      Calculates the truncated value of n, r, and returns the rth root
	      of x to the current scale.

	      If r is 0 or negative, this raises an error and causes bc(1) to
	      reset (see the RESET section).  It also raises an error and
	      causes bc(1) to reset if r is even and x is negative.

       gcd(a, b)
	      Returns the greatest common divisor (factor) of the truncated
	      absolute value of a and the truncated absolute value of b.

       lcm(a, b)
	      Returns the least common multiple of the truncated absolute
	      value of a and the truncated absolute value of b.

       pi(p)  Returns pi to p decimal places.

	      This is a transcendental function (see the Transcendental Func‐
	      tions subsection below).

       t(x)   Returns the tangent of x, which is assumed to be in radians.

	      This is a transcendental function (see the Transcendental Func‐
	      tions subsection below).

       a2(y, x)
	      Returns the arctangent of y/x, in radians.  If both y and x are
	      equal to 0, it raises an error and causes bc(1) to reset (see
	      the RESET section).  Otherwise, if x is greater than 0, it re‐
	      turns a(y/x).  If x is less than 0, and y is greater than or
	      equal to 0, it returns a(y/x)+pi.	 If x is less than 0, and y is
	      less than 0, it returns a(y/x)-pi.  If x is equal to 0, and y is
	      greater than 0, it returns pi/2.	If x is equal to 0, and y is
	      less than 0, it returns -pi/2.

	      This function is the same as the atan2() function in many pro‐
	      gramming languages.

	      This is a transcendental function (see the Transcendental Func‐
	      tions subsection below).

       sin(x) Returns the sine of x, which is assumed to be in radians.

	      This is an alias of s(x).

	      This is a transcendental function (see the Transcendental Func‐
	      tions subsection below).

       cos(x) Returns the cosine of x, which is assumed to be in radians.

	      This is an alias of c(x).

	      This is a transcendental function (see the Transcendental Func‐
	      tions subsection below).

       tan(x) Returns the tangent of x, which is assumed to be in radians.

	      If x is equal to 1 or -1, this raises an error and causes bc(1)
	      to reset (see the RESET section).

	      This is an alias of t(x).

	      This is a transcendental function (see the Transcendental Func‐
	      tions subsection below).

       atan(x)
	      Returns the arctangent of x, in radians.

	      This is an alias of a(x).

	      This is a transcendental function (see the Transcendental Func‐
	      tions subsection below).

       atan2(y, x)
	      Returns the arctangent of y/x, in radians.  If both y and x are
	      equal to 0, it raises an error and causes bc(1) to reset (see
	      the RESET section).  Otherwise, if x is greater than 0, it re‐
	      turns a(y/x).  If x is less than 0, and y is greater than or
	      equal to 0, it returns a(y/x)+pi.	 If x is less than 0, and y is
	      less than 0, it returns a(y/x)-pi.  If x is equal to 0, and y is
	      greater than 0, it returns pi/2.	If x is equal to 0, and y is
	      less than 0, it returns -pi/2.

	      This function is the same as the atan2() function in many pro‐
	      gramming languages.

	      This is an alias of a2(y, x).

	      This is a transcendental function (see the Transcendental Func‐
	      tions subsection below).

       r2d(x) Converts x from radians to degrees and returns the result.

	      This is a transcendental function (see the Transcendental Func‐
	      tions subsection below).

       d2r(x) Converts x from degrees to radians and returns the result.

	      This is a transcendental function (see the Transcendental Func‐
	      tions subsection below).

       frand(p)
	      Generates a pseudo-random number between 0 (inclusive) and 1
	      (exclusive) with the number of decimal digits after the decimal
	      point equal to the truncated absolute value of p.	 If p is not
	      0, then calling this function will change the value of seed.  If
	      p is 0, then 0 is returned, and seed is not changed.

       ifrand(i, p)
	      Generates a pseudo-random number that is between 0 (inclusive)
	      and the truncated absolute value of i (exclusive) with the num‐
	      ber of decimal digits after the decimal point equal to the trun‐
	      cated absolute value of p.  If the absolute value of i is
	      greater than or equal to 2, and p is not 0, then calling this
	      function will change the value of seed; otherwise, 0 is re‐
	      turned, and seed is not changed.

       i2rand(a, b)
	      Takes the truncated value of a and b and uses them as inclusive
	      bounds to enerate a pseudo-random integer.  If the difference of
	      the truncated values of a and b is 0, then the truncated value
	      is returned, and seed is not changed.  Otherwise, this function
	      will change the value of seed.

       srand(x)
	      Returns x with its sign flipped with probability 0.5.  In other
	      words, it randomizes the sign of x.

       brand()
	      Returns a random boolean value (either 0 or 1).

       band(a, b)
	      Takes the truncated absolute value of both a and b and calcu‐
	      lates and returns the result of the bitwise and operation be‐
	      tween them.

	      If you want to use signed two’s complement arguments, use s2u(x)
	      to convert.

       bor(a, b)
	      Takes the truncated absolute value of both a and b and calcu‐
	      lates and returns the result of the bitwise or operation between
	      them.

	      If you want to use signed two’s complement arguments, use s2u(x)
	      to convert.

       bxor(a, b)
	      Takes the truncated absolute value of both a and b and calcu‐
	      lates and returns the result of the bitwise xor operation be‐
	      tween them.

	      If you want to use signed two’s complement arguments, use s2u(x)
	      to convert.

       bshl(a, b)
	      Takes the truncated absolute value of both a and b and calcu‐
	      lates and returns the result of a bit-shifted left by b places.

	      If you want to use signed two’s complement arguments, use s2u(x)
	      to convert.

       bshr(a, b)
	      Takes the truncated absolute value of both a and b and calcu‐
	      lates and returns the truncated result of a bit-shifted right by
	      b places.

	      If you want to use signed two’s complement arguments, use s2u(x)
	      to convert.

       bnotn(x, n)
	      Takes the truncated absolute value of x and does a bitwise not
	      as though it has the same number of bytes as the truncated abso‐
	      lute value of n.

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       bnot8(x)
	      Does a bitwise not of the truncated absolute value of x as
	      though it has 8 binary digits (1 unsigned byte).

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       bnot16(x)
	      Does a bitwise not of the truncated absolute value of x as
	      though it has 16 binary digits (2 unsigned bytes).

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       bnot32(x)
	      Does a bitwise not of the truncated absolute value of x as
	      though it has 32 binary digits (4 unsigned bytes).

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       bnot64(x)
	      Does a bitwise not of the truncated absolute value of x as
	      though it has 64 binary digits (8 unsigned bytes).

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       bnot(x)
	      Does a bitwise not of the truncated absolute value of x as
	      though it has the minimum number of power of two unsigned bytes.

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       brevn(x, n)
	      Runs a bit reversal on the truncated absolute value of x as
	      though it has the same number of 8-bit bytes as the truncated
	      absolute value of n.

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       brev8(x)
	      Runs a bit reversal on the truncated absolute value of x as
	      though it has 8 binary digits (1 unsigned byte).

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       brev16(x)
	      Runs a bit reversal on the truncated absolute value of x as
	      though it has 16 binary digits (2 unsigned bytes).

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       brev32(x)
	      Runs a bit reversal on the truncated absolute value of x as
	      though it has 32 binary digits (4 unsigned bytes).

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       brev64(x)
	      Runs a bit reversal on the truncated absolute value of x as
	      though it has 64 binary digits (8 unsigned bytes).

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       brev(x)
	      Runs a bit reversal on the truncated absolute value of x as
	      though it has the minimum number of power of two unsigned bytes.

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       broln(x, p, n)
	      Does a left bitwise rotatation of the truncated absolute value
	      of x, as though it has the same number of unsigned 8-bit bytes
	      as the truncated absolute value of n, by the number of places
	      equal to the truncated absolute value of p modded by the 2 to
	      the power of the number of binary digits in n 8-bit bytes.

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       brol8(x, p)
	      Does a left bitwise rotatation of the truncated absolute value
	      of x, as though it has 8 binary digits (1 unsigned byte), by the
	      number of places equal to the truncated absolute value of p mod‐
	      ded by 2 to the power of 8.

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       brol16(x, p)
	      Does a left bitwise rotatation of the truncated absolute value
	      of x, as though it has 16 binary digits (2 unsigned bytes), by
	      the number of places equal to the truncated absolute value of p
	      modded by 2 to the power of 16.

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       brol32(x, p)
	      Does a left bitwise rotatation of the truncated absolute value
	      of x, as though it has 32 binary digits (4 unsigned bytes), by
	      the number of places equal to the truncated absolute value of p
	      modded by 2 to the power of 32.

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       brol64(x, p)
	      Does a left bitwise rotatation of the truncated absolute value
	      of x, as though it has 64 binary digits (8 unsigned bytes), by
	      the number of places equal to the truncated absolute value of p
	      modded by 2 to the power of 64.

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       brol(x, p)
	      Does a left bitwise rotatation of the truncated absolute value
	      of x, as though it has the minimum number of power of two un‐
	      signed 8-bit bytes, by the number of places equal to the trun‐
	      cated absolute value of p modded by 2 to the power of the number
	      of binary digits in the minimum number of 8-bit bytes.

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       brorn(x, p, n)
	      Does a right bitwise rotatation of the truncated absolute value
	      of x, as though it has the same number of unsigned 8-bit bytes
	      as the truncated absolute value of n, by the number of places
	      equal to the truncated absolute value of p modded by the 2 to
	      the power of the number of binary digits in n 8-bit bytes.

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       bror8(x, p)
	      Does a right bitwise rotatation of the truncated absolute value
	      of x, as though it has 8 binary digits (1 unsigned byte), by the
	      number of places equal to the truncated absolute value of p mod‐
	      ded by 2 to the power of 8.

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       bror16(x, p)
	      Does a right bitwise rotatation of the truncated absolute value
	      of x, as though it has 16 binary digits (2 unsigned bytes), by
	      the number of places equal to the truncated absolute value of p
	      modded by 2 to the power of 16.

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       bror32(x, p)
	      Does a right bitwise rotatation of the truncated absolute value
	      of x, as though it has 32 binary digits (2 unsigned bytes), by
	      the number of places equal to the truncated absolute value of p
	      modded by 2 to the power of 32.

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       bror64(x, p)
	      Does a right bitwise rotatation of the truncated absolute value
	      of x, as though it has 64 binary digits (2 unsigned bytes), by
	      the number of places equal to the truncated absolute value of p
	      modded by 2 to the power of 64.

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       bror(x, p)
	      Does a right bitwise rotatation of the truncated absolute value
	      of x, as though it has the minimum number of power of two un‐
	      signed 8-bit bytes, by the number of places equal to the trun‐
	      cated absolute value of p modded by 2 to the power of the number
	      of binary digits in the minimum number of 8-bit bytes.

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       bmodn(x, n)
	      Returns the modulus of the truncated absolute value of x by 2 to
	      the power of the multiplication of the truncated absolute value
	      of n and 8.

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       bmod8(x, n)
	      Returns the modulus of the truncated absolute value of x by 2 to
	      the power of 8.

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       bmod16(x, n)
	      Returns the modulus of the truncated absolute value of x by 2 to
	      the power of 16.

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       bmod32(x, n)
	      Returns the modulus of the truncated absolute value of x by 2 to
	      the power of 32.

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       bmod64(x, n)
	      Returns the modulus of the truncated absolute value of x by 2 to
	      the power of 64.

	      If you want to a use signed two’s complement argument, use
	      s2u(x) to convert.

       bunrev(t)
	      Assumes t is a bitwise-reversed number with an extra set bit one
	      place more significant than the real most significant bit (which
	      was the least significant bit in the original number).  This
	      number is reversed and returned without the extra set bit.

	      This function is used to implement other bitwise functions; it
	      is not meant to be used by users, but it can be.

       plz(x) If x is not equal to 0 and greater that -1 and less than 1, it
	      is printed with a leading zero, regardless of the use of the -z
	      option (see the OPTIONS section) and without a trailing newline.

	      Otherwise, x is printed normally, without a trailing newline.

       plznl(x)
	      If x is not equal to 0 and greater that -1 and less than 1, it
	      is printed with a leading zero, regardless of the use of the -z
	      option (see the OPTIONS section) and with a trailing newline.

	      Otherwise, x is printed normally, with a trailing newline.

       pnlz(x)
	      If x is not equal to 0 and greater that -1 and less than 1, it
	      is printed without a leading zero, regardless of the use of the
	      -z option (see the OPTIONS section) and without a trailing new‐
	      line.

	      Otherwise, x is printed normally, without a trailing newline.

       pnlznl(x)
	      If x is not equal to 0 and greater that -1 and less than 1, it
	      is printed without a leading zero, regardless of the use of the
	      -z option (see the OPTIONS section) and with a trailing newline.

	      Otherwise, x is printed normally, with a trailing newline.

       ubytes(x)
	      Returns the numbers of unsigned integer bytes required to hold
	      the truncated absolute value of x.

       sbytes(x)
	      Returns the numbers of signed, two’s-complement integer bytes
	      required to hold the truncated value of x.

       s2u(x) Returns x if it is non-negative.	If it is negative, then it
	      calculates what x would be as a 2’s-complement signed integer
	      and returns the non-negative integer that would have the same
	      representation in binary.

       s2un(x,n)
	      Returns x if it is non-negative.	If it is negative, then it
	      calculates what x would be as a 2’s-complement signed integer
	      with n bytes and returns the non-negative integer that would
	      have the same representation in binary.  If x cannot fit into n
	      2’s-complement signed bytes, it is truncated to fit.

       hex(x) Outputs the hexadecimal (base 16) representation of x.

	      This is a void function (see the Void Functions subsection of
	      the FUNCTIONS section).

       binary(x)
	      Outputs the binary (base 2) representation of x.

	      This is a void function (see the Void Functions subsection of
	      the FUNCTIONS section).

       output(x, b)
	      Outputs the base b representation of x.

	      This is a void function (see the Void Functions subsection of
	      the FUNCTIONS section).

       uint(x)
	      Outputs the representation, in binary and hexadecimal, of x as
	      an unsigned integer in as few power of two bytes as possible.
	      Both outputs are split into bytes separated by spaces.

	      If x is not an integer or is negative, an error message is
	      printed instead, but bc(1) is not reset (see the RESET section).

	      This is a void function (see the Void Functions subsection of
	      the FUNCTIONS section).

       int(x) Outputs the representation, in binary and hexadecimal, of x as a
	      signed, two’s-complement integer in as few power of two bytes as
	      possible.	 Both outputs are split into bytes separated by spa‐
	      ces.

	      If x is not an integer, an error message is printed instead, but
	      bc(1) is not reset (see the RESET section).

	      This is a void function (see the Void Functions subsection of
	      the FUNCTIONS section).

       uintn(x, n)
	      Outputs the representation, in binary and hexadecimal, of x as
	      an unsigned integer in n bytes.  Both outputs are split into
	      bytes separated by spaces.

	      If x is not an integer, is negative, or cannot fit into n bytes,
	      an error message is printed instead, but bc(1) is not reset (see
	      the RESET section).

	      This is a void function (see the Void Functions subsection of
	      the FUNCTIONS section).

       intn(x, n)
	      Outputs the representation, in binary and hexadecimal, of x as a
	      signed, two’s-complement integer in n bytes.  Both outputs are
	      split into bytes separated by spaces.

	      If x is not an integer or cannot fit into n bytes, an error mes‐
	      sage is printed instead, but bc(1) is not reset (see the RESET
	      section).

	      This is a void function (see the Void Functions subsection of
	      the FUNCTIONS section).

       uint8(x)
	      Outputs the representation, in binary and hexadecimal, of x as
	      an unsigned integer in 1 byte.  Both outputs are split into
	      bytes separated by spaces.

	      If x is not an integer, is negative, or cannot fit into 1 byte,
	      an error message is printed instead, but bc(1) is not reset (see
	      the RESET section).

	      This is a void function (see the Void Functions subsection of
	      the FUNCTIONS section).

       int8(x)
	      Outputs the representation, in binary and hexadecimal, of x as a
	      signed, two’s-complement integer in 1 byte.  Both outputs are
	      split into bytes separated by spaces.

	      If x is not an integer or cannot fit into 1 byte, an error mes‐
	      sage is printed instead, but bc(1) is not reset (see the RESET
	      section).

	      This is a void function (see the Void Functions subsection of
	      the FUNCTIONS section).

       uint16(x)
	      Outputs the representation, in binary and hexadecimal, of x as
	      an unsigned integer in 2 bytes.  Both outputs are split into
	      bytes separated by spaces.

	      If x is not an integer, is negative, or cannot fit into 2 bytes,
	      an error message is printed instead, but bc(1) is not reset (see
	      the RESET section).

	      This is a void function (see the Void Functions subsection of
	      the FUNCTIONS section).

       int16(x)
	      Outputs the representation, in binary and hexadecimal, of x as a
	      signed, two’s-complement integer in 2 bytes.  Both outputs are
	      split into bytes separated by spaces.

	      If x is not an integer or cannot fit into 2 bytes, an error mes‐
	      sage is printed instead, but bc(1) is not reset (see the RESET
	      section).

	      This is a void function (see the Void Functions subsection of
	      the FUNCTIONS section).

       uint32(x)
	      Outputs the representation, in binary and hexadecimal, of x as
	      an unsigned integer in 4 bytes.  Both outputs are split into
	      bytes separated by spaces.

	      If x is not an integer, is negative, or cannot fit into 4 bytes,
	      an error message is printed instead, but bc(1) is not reset (see
	      the RESET section).

	      This is a void function (see the Void Functions subsection of
	      the FUNCTIONS section).

       int32(x)
	      Outputs the representation, in binary and hexadecimal, of x as a
	      signed, two’s-complement integer in 4 bytes.  Both outputs are
	      split into bytes separated by spaces.

	      If x is not an integer or cannot fit into 4 bytes, an error mes‐
	      sage is printed instead, but bc(1) is not reset (see the RESET
	      section).

	      This is a void function (see the Void Functions subsection of
	      the FUNCTIONS section).

       uint64(x)
	      Outputs the representation, in binary and hexadecimal, of x as
	      an unsigned integer in 8 bytes.  Both outputs are split into
	      bytes separated by spaces.

	      If x is not an integer, is negative, or cannot fit into 8 bytes,
	      an error message is printed instead, but bc(1) is not reset (see
	      the RESET section).

	      This is a void function (see the Void Functions subsection of
	      the FUNCTIONS section).

       int64(x)
	      Outputs the representation, in binary and hexadecimal, of x as a
	      signed, two’s-complement integer in 8 bytes.  Both outputs are
	      split into bytes separated by spaces.

	      If x is not an integer or cannot fit into 8 bytes, an error mes‐
	      sage is printed instead, but bc(1) is not reset (see the RESET
	      section).

	      This is a void function (see the Void Functions subsection of
	      the FUNCTIONS section).

       hex_uint(x, n)
	      Outputs the representation of the truncated absolute value of x
	      as an unsigned integer in hexadecimal using n bytes.  Not all of
	      the value will be output if n is too small.

	      This is a void function (see the Void Functions subsection of
	      the FUNCTIONS section).

       binary_uint(x, n)
	      Outputs the representation of the truncated absolute value of x
	      as an unsigned integer in binary using n bytes.  Not all of the
	      value will be output if n is too small.

	      This is a void function (see the Void Functions subsection of
	      the FUNCTIONS section).

       output_uint(x, n)
	      Outputs the representation of the truncated absolute value of x
	      as an unsigned integer in the current obase (see the SYNTAX sec‐
	      tion) using n bytes.  Not all of the value will be output if n
	      is too small.

	      This is a void function (see the Void Functions subsection of
	      the FUNCTIONS section).

       output_byte(x, i)
	      Outputs byte i of the truncated absolute value of x, where 0 is
	      the least significant byte and number_of_bytes - 1 is the most
	      significant byte.

	      This is a void function (see the Void Functions subsection of
	      the FUNCTIONS section).

   Transcendental Functions
       All transcendental functions can return slightly inaccurate results, up
       to 1 ULP (https://en.wikipedia.org/wiki/Unit_in_the_last_place).	 This
       is unavoidable, and the article at https://people.eecs.berke‐
       ley.edu/~wkahan/LOG10HAF.TXT explains why it is impossible and unneces‐
       sary to calculate exact results for the transcendental functions.

       Because of the possible inaccuracy, I recommend that users call those
       functions with the precision (scale) set to at least 1 higher than is
       necessary.  If exact results are absolutely required, users can double
       the precision (scale) and then truncate.

       The transcendental functions in the standard math library are:

       • s(x)

       • c(x)

       • a(x)

       • l(x)

       • e(x)

       • j(x, n)

       The transcendental functions in the extended math library are:

       • l2(x)

       • l10(x)

       • log(x, b)

       • pi(p)

       • t(x)

       • a2(y, x)

       • sin(x)

       • cos(x)

       • tan(x)

       • atan(x)

       • atan2(y, x)

       • r2d(x)

       • d2r(x)

RESET
       When bc(1) encounters an error or a signal that it has a non-default
       handler for, it resets.	This means that several things happen.

       First, any functions that are executing are stopped and popped off the
       stack.  The behavior is not unlike that of exceptions in programming
       languages.  Then the execution point is set so that any code waiting to
       execute (after all functions returned) is skipped.

       Thus, when bc(1) resets, it skips any remaining code waiting to be exe‐
       cuted.  Then, if it is interactive mode, and the error was not a fatal
       error (see the EXIT STATUS section), it asks for more input; otherwise,
       it exits with the appropriate return code.

       Note that this reset behavior is different from the GNU bc(1), which
       attempts to start executing the statement right after the one that
       caused an error.

PERFORMANCE
       Most bc(1) implementations use char types to calculate the value of 1
       decimal digit at a time, but that can be slow.  This bc(1) does some‐
       thing different.

       It uses large integers to calculate more than 1 decimal digit at a
       time.  If built in a environment where BC_LONG_BIT (see the LIMITS sec‐
       tion) is 64, then each integer has 9 decimal digits.  If built in an
       environment where BC_LONG_BIT is 32 then each integer has 4 decimal
       digits.	This value (the number of decimal digits per large integer) is
       called BC_BASE_DIGS.

       The actual values of BC_LONG_BIT and BC_BASE_DIGS can be queried with
       the limits statement.

       In addition, this bc(1) uses an even larger integer for overflow check‐
       ing.  This integer type depends on the value of BC_LONG_BIT, but is al‐
       ways at least twice as large as the integer type used to store digits.

LIMITS
       The following are the limits on bc(1):

       BC_LONG_BIT
	      The number of bits in the long type in the environment where
	      bc(1) was built.	This determines how many decimal digits can be
	      stored in a single large integer (see the PERFORMANCE section).

       BC_BASE_DIGS
	      The number of decimal digits per large integer (see the PERFOR‐
	      MANCE section).  Depends on BC_LONG_BIT.

       BC_BASE_POW
	      The max decimal number that each large integer can store (see
	      BC_BASE_DIGS) plus 1.  Depends on BC_BASE_DIGS.

       BC_OVERFLOW_MAX
	      The max number that the overflow type (see the PERFORMANCE sec‐
	      tion) can hold.  Depends on BC_LONG_BIT.

       BC_BASE_MAX
	      The maximum output base.	Set at BC_BASE_POW.

       BC_DIM_MAX
	      The maximum size of arrays.  Set at SIZE_MAX-1.

       BC_SCALE_MAX
	      The maximum scale.  Set at BC_OVERFLOW_MAX-1.

       BC_STRING_MAX
	      The maximum length of strings.  Set at BC_OVERFLOW_MAX-1.

       BC_NAME_MAX
	      The maximum length of identifiers.  Set at BC_OVERFLOW_MAX-1.

       BC_NUM_MAX
	      The maximum length of a number (in decimal digits), which in‐
	      cludes digits after the decimal point.  Set at BC_OVER‐
	      FLOW_MAX-1.

       BC_RAND_MAX
	      The maximum integer (inclusive) returned by the rand() operand.
	      Set at 2^BC_LONG_BIT-1.

       Exponent
	      The maximum allowable exponent (positive or negative).  Set at
	      BC_OVERFLOW_MAX.

       Number of vars
	      The maximum number of vars/arrays.  Set at SIZE_MAX-1.

       The actual values can be queried with the limits statement.

       These limits are meant to be effectively non-existent; the limits are
       so large (at least on 64-bit machines) that there should not be any
       point at which they become a problem.  In fact, memory should be ex‐
       hausted before these limits should be hit.

ENVIRONMENT VARIABLES
       As non-portable extensions, bc(1) recognizes the following environment
       variables:

       POSIXLY_CORRECT
	      If this variable exists (no matter the contents), bc(1) behaves
	      as if the -s option was given.

       BC_ENV_ARGS
	      This is another way to give command-line arguments to bc(1).
	      They should be in the same format as all other command-line ar‐
	      guments.	These are always processed first, so any files given
	      in BC_ENV_ARGS will be processed before arguments and files
	      given on the command-line.  This gives the user the ability to
	      set up “standard” options and files to be used at every invoca‐
	      tion.  The most useful thing for such files to contain would be
	      useful functions that the user might want every time bc(1) runs.

	      The code that parses BC_ENV_ARGS will correctly handle quoted
	      arguments, but it does not understand escape sequences.  For ex‐
	      ample, the string “/home/gavin/some bc file.bc” will be cor‐
	      rectly parsed, but the string “/home/gavin/some "bc" file.bc”
	      will include the backslashes.

	      The quote parsing will handle either kind of quotes, ’ or “.
	      Thus, if you have a file with any number of single quotes in the
	      name, you can use double quotes as the outside quotes, as in
	      “some `bc' file.bc”, and vice versa if you have a file with dou‐
	      ble quotes.  However, handling a file with both kinds of quotes
	      in BC_ENV_ARGS is not supported due to the complexity of the
	      parsing, though such files are still supported on the com‐
	      mand-line where the parsing is done by the shell.

       BC_LINE_LENGTH
	      If this environment variable exists and contains an integer that
	      is greater than 1 and is less than UINT16_MAX (2^16-1), bc(1)
	      will output lines to that length, including the backslash (\).
	      The default line length is 70.

	      The special value of 0 will disable line length checking and
	      print numbers without regard to line length and without back‐
	      slashes and newlines.

       BC_BANNER
	      If this environment variable exists and contains an integer,
	      then a non-zero value activates the copyright banner when bc(1)
	      is in interactive mode, while zero deactivates it.

	      If bc(1) is not in interactive mode (see the INTERACTIVE MODE
	      section), then this environment variable has no effect because
	      bc(1) does not print the banner when not in interactive mode.

	      This environment variable overrides the default, which can be
	      queried with the -h or --help options.

       BC_SIGINT_RESET
	      If bc(1) is not in interactive mode (see the INTERACTIVE MODE
	      section), then this environment variable has no effect because
	      bc(1) exits on SIGINT when not in interactive mode.

	      However, when bc(1) is in interactive mode, then if this envi‐
	      ronment variable exists and contains an integer, a non-zero
	      value makes bc(1) reset on SIGINT, rather than exit, and zero
	      makes bc(1) exit.	 If this environment variable exists and is
	      not an integer, then bc(1) will exit on SIGINT.

	      This environment variable overrides the default, which can be
	      queried with the -h or --help options.

       BC_TTY_MODE
	      If TTY mode is not available (see the TTY MODE section), then
	      this environment variable has no effect.

	      However, when TTY mode is available, then if this environment
	      variable exists and contains an integer, then a non-zero value
	      makes bc(1) use TTY mode, and zero makes bc(1) not use TTY mode.

	      This environment variable overrides the default, which can be
	      queried with the -h or --help options.

       BC_PROMPT
	      If TTY mode is not available (see the TTY MODE section), then
	      this environment variable has no effect.

	      However, when TTY mode is available, then if this environment
	      variable exists and contains an integer, a non-zero value makes
	      bc(1) use a prompt, and zero or a non-integer makes bc(1) not
	      use a prompt.  If this environment variable does not exist and
	      BC_TTY_MODE does, then the value of the BC_TTY_MODE environment
	      variable is used.

	      This environment variable and the BC_TTY_MODE environment vari‐
	      able override the default, which can be queried with the -h or
	      --help options.

       BC_EXPR_EXIT
	      If any expressions or expression files are given on the com‐
	      mand-line with -e, --expression, -f, or --file, then if this en‐
	      vironment variable exists and contains an integer, a non-zero
	      value makes bc(1) exit after executing the expressions and ex‐
	      pression files, and a zero value makes bc(1) not exit.

	      This environment variable overrides the default, which can be
	      queried with the -h or --help options.

       BC_DIGIT_CLAMP
	      When parsing numbers and if this environment variable exists and
	      contains an integer, a non-zero value makes bc(1) clamp digits
	      that are greater than or equal to the current ibase so that all
	      such digits are considered equal to the ibase minus 1, and a
	      zero value disables such clamping so that those digits are al‐
	      ways equal to their value, which is multiplied by the power of
	      the ibase.

	      This never applies to single-digit numbers, as per the standard
	      (see the STANDARDS section).

	      This environment variable overrides the default, which can be
	      queried with the -h or --help options.

EXIT STATUS
       bc(1) returns the following exit statuses:

       0      No error.

       1      A math error occurred.  This follows standard practice of using
	      1 for expected errors, since math errors will happen in the
	      process of normal execution.

	      Math errors include divide by 0, taking the square root of a
	      negative number, using a negative number as a bound for the
	      pseudo-random number generator, attempting to convert a negative
	      number to a hardware integer, overflow when converting a number
	      to a hardware integer, overflow when calculating the size of a
	      number, and attempting to use a non-integer where an integer is
	      required.

	      Converting to a hardware integer happens for the second operand
	      of the power (^), places (@), left shift (<<), and right shift
	      (>>) operators and their corresponding assignment operators.

       2      A parse error occurred.

	      Parse errors include unexpected EOF, using an invalid character,
	      failing to find the end of a string or comment, using a token
	      where it is invalid, giving an invalid expression, giving an in‐
	      valid print statement, giving an invalid function definition,
	      attempting to assign to an expression that is not a named ex‐
	      pression (see the Named Expressions subsection of the SYNTAX
	      section), giving an invalid auto list, having a duplicate
	      auto/function parameter, failing to find the end of a code
	      block, attempting to return a value from a void function, at‐
	      tempting to use a variable as a reference, and using any exten‐
	      sions when the option -s or any equivalents were given.

       3      A runtime error occurred.

	      Runtime errors include assigning an invalid number to any global
	      (ibase, obase, or scale), giving a bad expression to a read()
	      call, calling read() inside of a read() call, type errors, pass‐
	      ing the wrong number of arguments to functions, attempting to
	      call an undefined function, and attempting to use a void func‐
	      tion call as a value in an expression.

       4      A fatal error occurred.

	      Fatal errors include memory allocation errors, I/O errors, fail‐
	      ing to open files, attempting to use files that do not have only
	      ASCII characters (bc(1) only accepts ASCII characters), attempt‐
	      ing to open a directory as a file, and giving invalid com‐
	      mand-line options.

       The exit status 4 is special; when a fatal error occurs, bc(1) always
       exits and returns 4, no matter what mode bc(1) is in.

       The other statuses will only be returned when bc(1) is not in interac‐
       tive mode (see the INTERACTIVE MODE section), since bc(1) resets its
       state (see the RESET section) and accepts more input when one of those
       errors occurs in interactive mode.  This is also the case when interac‐
       tive mode is forced by the -i flag or --interactive option.

       These exit statuses allow bc(1) to be used in shell scripting with er‐
       ror checking, and its normal behavior can be forced by using the -i
       flag or --interactive option.

INTERACTIVE MODE
       Per the standard (see the STANDARDS section), bc(1) has an interactive
       mode and a non-interactive mode.	 Interactive mode is turned on auto‐
       matically when both stdin and stdout are hooked to a terminal, but the
       -i flag and --interactive option can turn it on in other situations.

       In interactive mode, bc(1) attempts to recover from errors (see the RE‐
       SET section), and in normal execution, flushes stdout as soon as execu‐
       tion is done for the current input.  bc(1) may also reset on SIGINT in‐
       stead of exit, depending on the contents of, or default for, the
       BC_SIGINT_RESET environment variable (see the ENVIRONMENT VARIABLES
       section).

TTY MODE
       If stdin, stdout, and stderr are all connected to a TTY, then “TTY
       mode” is considered to be available, and thus, bc(1) can turn on TTY
       mode, subject to some settings.

       If there is the environment variable BC_TTY_MODE in the environment
       (see the ENVIRONMENT VARIABLES section), then if that environment vari‐
       able contains a non-zero integer, bc(1) will turn on TTY mode when
       stdin, stdout, and stderr are all connected to a TTY.  If the
       BC_TTY_MODE environment variable exists but is not a non-zero integer,
       then bc(1) will not turn TTY mode on.

       If the environment variable BC_TTY_MODE does not exist, the default
       setting is used.	 The default setting can be queried with the -h or
       --help options.

       TTY mode is different from interactive mode because interactive mode is
       required in the bc(1) standard (see the STANDARDS section), and inter‐
       active mode requires only stdin and stdout to be connected to a termi‐
       nal.

   Command-Line History
       Command-line history is only enabled if TTY mode is, i.e., that stdin,
       stdout, and stderr are connected to a TTY and the BC_TTY_MODE environ‐
       ment variable (see the ENVIRONMENT VARIABLES section) and its default
       do not disable TTY mode.	 See the COMMAND LINE HISTORY section for more
       information.

   Prompt
       If TTY mode is available, then a prompt can be enabled.	Like TTY mode
       itself, it can be turned on or off with an environment variable:
       BC_PROMPT (see the ENVIRONMENT VARIABLES section).

       If the environment variable BC_PROMPT exists and is a non-zero integer,
       then the prompt is turned on when stdin, stdout, and stderr are con‐
       nected to a TTY and the -P and --no-prompt options were not used.  The
       read prompt will be turned on under the same conditions, except that
       the -R and --no-read-prompt options must also not be used.

       However, if BC_PROMPT does not exist, the prompt can be enabled or dis‐
       abled with the BC_TTY_MODE environment variable, the -P and --no-prompt
       options, and the -R and --no-read-prompt options.  See the ENVIRONMENT
       VARIABLES and OPTIONS sections for more details.

SIGNAL HANDLING
       Sending a SIGINT will cause bc(1) to do one of two things.

       If bc(1) is not in interactive mode (see the INTERACTIVE MODE section),
       or the BC_SIGINT_RESET environment variable (see the ENVIRONMENT VARI‐
       ABLES section), or its default, is either not an integer or it is zero,
       bc(1) will exit.

       However, if bc(1) is in interactive mode, and the BC_SIGINT_RESET or
       its default is an integer and non-zero, then bc(1) will stop executing
       the current input and reset (see the RESET section) upon receiving a
       SIGINT.

       Note that “current input” can mean one of two things.  If bc(1) is pro‐
       cessing input from stdin in interactive mode, it will ask for more in‐
       put.  If bc(1) is processing input from a file in interactive mode, it
       will stop processing the file and start processing the next file, if
       one exists, or ask for input from stdin if no other file exists.

       This means that if a SIGINT is sent to bc(1) as it is executing a file,
       it can seem as though bc(1) did not respond to the signal since it will
       immediately start executing the next file.  This is by design; most
       files that users execute when interacting with bc(1) have function def‐
       initions, which are quick to parse.  If a file takes a long time to ex‐
       ecute, there may be a bug in that file.	The rest of the files could
       still be executed without problem, allowing the user to continue.

       SIGTERM and SIGQUIT cause bc(1) to clean up and exit, and it uses the
       default handler for all other signals.  The one exception is SIGHUP; in
       that case, and only when bc(1) is in TTY mode (see the TTY MODE sec‐
       tion), a SIGHUP will cause bc(1) to clean up and exit.

COMMAND LINE HISTORY
       bc(1) supports interactive command-line editing.

       If bc(1) can be in TTY mode (see the TTY MODE section), history can be
       enabled.	 This means that command-line history can only be enabled when
       stdin, stdout, and stderr are all connected to a TTY.

       Like TTY mode itself, it can be turned on or off with the environment
       variable BC_TTY_MODE (see the ENVIRONMENT VARIABLES section).

       If history is enabled, previous lines can be recalled and edited with
       the arrow keys.

       Note: tabs are converted to 8 spaces.

LOCALES
       This bc(1) ships with support for adding error messages for different
       locales and thus, supports LC_MESSAGES.

SEE ALSO
       dc(1)

STANDARDS
       bc(1) is compliant with the IEEE Std 1003.1-2017 (“POSIX.1-2017”) spec‐
       ification at https://pubs.opengroup.org/onlinepubs/9699919799/utili‐
       ties/bc.html .  The flags -efghiqsvVw, all long options, and the exten‐
       sions noted above are extensions to that specification.

       In addition, the behavior of the quit implements an interpretation of
       that specification that is different from all known implementations.
       For more information see the Statements subsection of the SYNTAX sec‐
       tion.

       Note that the specification explicitly says that bc(1) only accepts
       numbers that use a period (.) as a radix point, regardless of the value
       of LC_NUMERIC.

       This bc(1) supports error messages for different locales, and thus, it
       supports LC_MESSAGES.

BUGS
       Before version 6.1.0, this bc(1) had incorrect behavior for the quit
       statement.

       No other bugs are known.	 Report bugs at https://git.gavin‐
       howard.com/gavin/bc .

AUTHORS
       Gavin D. Howard ⟨gavin@gavinhoward.com⟩ and contributors.



Gavin D. Howard			  August 2024				 BC(1)