我正在 Matlab 中编写一个简单的程序,并且想知道确保用户输入的值是正确整数的最佳方法。
我目前正在使用这个:
while((num_dice < 1) || isempty(num_dice))
num_dice = input('Enter the number of dice to roll: ');
end
但我真的知道一定有更好的方法,因为这并不总是有效。我还想添加错误检查和 try catch 块。我是 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
这似乎有效。这有什么明显的问题吗? isinteger 由接受的答案定义
以下内容可以直接在代码中使用,并检查非整数输入,包括空值、无限值和虚数:
isInteger = ~isempty(num_dice) ...
&& isnumeric(num_dice) ...
&& isreal(num_dice) ...
&& isfinite(num_dice) ...
&& (num_dice == fix(num_dice));
以上仅适用于标量输入。要测试多维数组是否仅包含整数,可以使用:
isInteger = ~isempty(x) ...
&& isnumeric(x) ...
&& isreal(x) ...
&& all(isfinite(x)) ...
&& all(x == fix(x))
EDIT
这些测试针对any整数值。要将有效值限制为正整数,请添加num_dice > 0
as in @MajorApus 的回答.
您可以使用上面的内容通过循环强制用户输入整数,直到他们屈服于您的要求:
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)