MATLAB爱好者论坛-LabFans.com

MATLAB爱好者论坛-LabFans.com (https://www.labfans.com/bbs/index.php)
-   资料存档 (https://www.labfans.com/bbs/forumdisplay.php?f=72)
-   -   强制用户在Matlab中输入整数的最佳方法 (https://www.labfans.com/bbs/showthread.php?t=26534)

poster 2019-12-14 20:13

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

我目前正在使用此:

while((num_dice < 1) || isempty(num_dice)) num_dice = input('Enter the number of dice to roll: '); end 但是我真的知道必须有一个更好的方法,因为这并不总是有效。我还想添加错误检查ala try catch块。我是Matlab的新手,所以在此方面的任何投入都是很棒的。

[B]编辑2:[/B]

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由接受的答案定义



[B]回答:[/B]

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

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)) [B]编辑[/B]

这些将测试[I]任何[/I]整数值。要将有效值限制为正整数,请添加一个num_dice > 0如[URL="https://stackoverflow.com/questions/5236806/best-way-to-force-a-user-to-input-a-integer-in-matlab/5236895#5236895"]@MajorApus的答案中所示[/URL] 。

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

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

[url=https://stackoverflow.com/questions/5236806]更多&回答...[/url]


所有时间均为北京时间。现在的时间是 10:55

Powered by vBulletin
版权所有 ©2000 - 2025,Jelsoft Enterprises Ltd.