4.7 数据类型的自动转换

许多运算符和函数可以处理混合数据类型。例如:

uint8 (1) + 1
    ⇒   2

single (1) + 1
    ⇒   2

min (single (1), 0)
    ⇒   0

上述结果分别为 uint8、single 和 single 类型。这是为了与 MATLAB 兼容。有效的混合运算定义如下:

混合运算 结果
double OP singlesingle
double OP integerinteger
double OP chardouble
double OP logicaldouble
single OP integerinteger
single OP charsingle
single OP logicalsingle

当函数期望接收 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 仍保持双精度类型。


版权所有 © 2024-2026 Octave中文网

ICP备案/许可证号:黑ICP备2024030411号-4