强制用户在Matlab中输入整数的最佳方法

Tan*_*ner 5 matlab

我在Matlab编写一个简单的程序,我想知道确保用户输入的值是一个合适的整数的最佳方法.

我目前正在使用这个:

while((num_dice < 1) || isempty(num_dice))
    num_dice = input('Enter the number of dice to roll: ');
end
Run Code Online (Sandbox Code Playgroud)

但是我真的知道必须有更好的方法,因为这不会一直有效.我还想添加错误检查ala try try块.我是Matlab的新手,所以对此的任何输入都会很棒.

EDIT2:

try
    while(~isinteger(num_dice) || (num_dice < 1))
        num_dice = sscanf(input('Enter the number of dice to roll: ', 's'), '%d');
    end

    while(~isinteger(faces) || (faces < 1))
        faces = sscanf(input('Enter the number of faces each die has: ', 's'), '%d');
    end

    while(~isinteger(rolls) || (rolls < 1))
        rolls = sscanf(input('Enter the number of trials: ', 's'), '%d');
    end
catch
    disp('Invalid number!')
end
Run Code Online (Sandbox Code Playgroud)

这似乎有效.这有什么明显的错误吗?isinteger由接受的答案定义

b3.*_*b3. 7

以下内容可以直接在您的代码中使用,并检查非整数输入,包括空值,无限值和虚数值:

isInteger = ~isempty(num_dice) ...
            && isnumeric(num_dice) ...
            && isreal(num_dice) ...
            && isfinite(num_dice) ...
            && (num_dice == fix(num_dice));
Run Code Online (Sandbox Code Playgroud)

以上内容仅适用于标量输入.要测试多维数组是否只包含整数,您可以使用:

isInteger = ~isempty(x) ...
            && isnumeric(x) ...
            && isreal(x) ...
            && all(isfinite(x)) ...
            && all(x == fix(x))
Run Code Online (Sandbox Code Playgroud)

编辑

这些测试任何整数值.要将有效值限制为正整数num_dice > 0,请在@ MajorApus的答案中添加as .

您可以使用上述方法强制用户通过循环输入一个整数,直到它们屈服于您的需求为止:

while ~(~isempty(num_dice) ...
            && isnumeric(num_dice) ...
            && isreal(num_dice) ...
            && isfinite(num_dice) ...
            && (num_dice == fix(num_dice)) ...
            && (num_dice > 0))
    num_dice = input('Enter the number of dice to roll: ');
end
Run Code Online (Sandbox Code Playgroud)


Mie*_*ter 6

试试这个,根据需要修改它.

function answer = isint(n)

if size(n) == [1 1]
    answer = isreal(n) && isnumeric(n) && round(n) == n &&  n >0;
else
    answer = false;
end
Run Code Online (Sandbox Code Playgroud)