4.7 Автоматическое преобразование типов данных
Многие операторы и функции могут работать со смешанными типами данных. Например,
uint8 (1) + 1
⇒ 2
single (1) + 1
⇒ 2
min (single (1), 0)
⇒ 0 где результаты имеют типы uint8, single и single соответственно. Это сделано для совместимости с MATLAB. Допустимые операции со смешанными типами определены следующим образом:
| Операция со смешанными типами | Результат | ||
|---|---|---|---|
| double OP single | single | ||
| double OP integer | integer | ||
| double OP char | double | ||
| double OP logical | double | ||
| single OP integer | integer | ||
| single OP char | single | ||
| single OP logical | single |
Если функции ожидают значение типа double, но им передаются значения других типов, автоматическое преобразование зависит от функции:
a = det (int8 ([1 2; 3 4]))
⇒ a = -2
class (a)
⇒ double
a = eig (int8 ([1 2; 3 4]))
⇒ error: eig: wrong type argument 'int8 matrix' Если оба операнда — целые числа, но разной разрядности, то в некоторых случаях они преобразуются к большей разрядности, а в других возникает ошибка:
a = min (int8 (100), int16 (200))
⇒ 100
class (a)
⇒ int16
int8 (100) + int16 (200)
⇒ error: binary operator '+' not implemented
for 'int8 scalar' by 'int16 scalar' operations Для двух целочисленных операндов обычно требуется, чтобы оба были знаковыми или оба беззнаковыми. Смешение знакового и беззнакового типов обычно приводит к ошибке, даже если у них одинаковая разрядность.
min (int16 (100), uint16 (200)) ⇒ error: min: cannot compute min (int16 scalar, uint16 scalar)
При индексированном присваивании со смешанными типами тип не изменяется. Например,
x = ones (2, 2);
x(1, 1) = single (2)
⇒ x = 2 1
1 1 где x по-прежнему имеет тип двойной точности.
© 1996–2026 The Octave Project Developers
Permission is granted to make and distribute verbatim copies of this manual provided the copyright notice and this permission notice are preserved on all copies.
Permission is granted to copy and distribute modified versions of this manual under the conditions for verbatim copying, provided that the entire resulting derived work is distributed under the terms of a permission notice identical to this one.Permission is granted to copy and distribute translations of this manual into another language, under the above conditions for modified versions.
https://docs.octave.org/v9.4.0/Automatic-Conversion-of-Data-Types.html