强制用户在Matlab中输入整数的最佳方法 [英] Best way to force a user to input an integer in Matlab

查看:676
本文介绍了强制用户在Matlab中输入整数的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm writing a simple program in Matlab and am wondering the best way to ensure that the value a user is inputting is a proper integer.

我目前正在使用此

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

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

However I really know there must be a better way, because this doesn't work all the time. I would also like to add error checking ala a try catch block. I'm brand new to Matlab so any input on this would be great.

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

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

This seems to be working. Is there anything noticeably wrong with this? isinteger is defined by the accepted answer

推荐答案

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

The following can be used directly in your code and checks against non-integer input including empty, infinite and imaginary values:

isInteger = ~isempty(num_dice) ...
            && isnumeric(num_dice) ...
            && isreal(num_dice) ...
            && isfinite(num_dice) ...
            && (num_dice == fix(num_dice));

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

The above will only work correctly for scalar input. To test whether a multi-dimensional array contains only integers you can use:

isInteger = ~isempty(x) ...
            && isnumeric(x) ...
            && isreal(x) ...
            && all(isfinite(x)) ...
            && all(x == fix(x))

编辑

这些对 any 整数值的测试.要将有效值限制为正整数,请在

These test for any integer values. To restrict the valid values to positive integers add a num_dice > 0 as in @MajorApus's answer.

您可以使用上面的代码通过循环来强制用户输入整数,直到他们屈服于您的需求为止:

You can use the above to force the user to input an integer by looping until they succumb to your demands:

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

这篇关于强制用户在Matlab中输入整数的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆