Main Content

mustBeInteger

验证值为整数

说明

示例

如果 value 不包含整数值,mustBeInteger(value) 会引发错误。此函数测试数字是否带有小数部分。此处不考虑值的数据类型。mustBeInteger 不返回值。

mustBeInteger 调用以下函数来确定 value 是否为整数:

支持的类:重载 mustBeInteger 调用的函数的所有数值类、logical 和 MATLAB® 类。

此函数忽略输入参量中的空值。因此,当属性或函数参量值为空时,不会引发错误。

示例

全部折叠

验证计算结果是整数值。

A = randi(9)/randi(9);
mustBeInteger(A)
Values must be integer.

如果两个随机整数相除的结果带有小数部分,mustBeInteger 会引发错误。

此类将属性的值限制为仅允许整数。

classdef MyClass
   properties
      Prop1 {mustBeInteger}
   end
end

创建一个对象,并向其属性赋值。将两个随机整数相除,得到的可以是整数,也可以是带有小数部分的数。

obj = MyClass;
obj.Prop1 = randi(9)/randi(9);
Error setting 'Prop1' property of 'MyClass' class. Value must be integer.

当您向属性赋值时,MATLAB 会使用赋给属性的值调用 mustBeInteger。当这些特定随机整数的除法运算的结果值不是整数时,mustBeInteger 将引发错误。

此函数将输入参量限制为不带小数部分的值。

function r = mbInteger(A,idx)
    arguments
        A (1,:) {mustBeNumeric}
        idx (1,1) {mustBeInteger}
    end
    r = A(idx).^2;
end

使用非整数值调用该函数会导致 mustBeInteger 引发错误。将两个随机整数相除,得到的可以是整数,也可以是带有小数部分的数。

idx = randi(9)/randi(9);
A = rand(1,10);
r = mbInteger(A,idx);
Error using mbInteger 
 r = mbInteger(A,idx);
                 ↑
Invalid input argument at position 2. Value must be integer.

输入参数

全部折叠

要验证的值,指定为标量或由以下任一类型的值组成的数组:

其他数据类型会导致错误。

提示

  • mustBeInteger 用于属性和函数参量验证。

扩展功能

C/C++ 代码生成
使用 MATLAB® Coder™ 生成 C 代码和 C++ 代码。

版本历史记录

在 R2017a 中推出