Labfans是一个针对大学生、工程师和科研工作者的技术社区。 论坛首页 | 联系我们(Contact Us)
MATLAB爱好者论坛-LabFans.com
返回   MATLAB爱好者论坛-LabFans.com > 其它 > 资料存档
资料存档 资料存档
回复
 
主题工具 显示模式
旧 2019-12-14, 20:13   #1
poster
高级会员
 
注册日期: 2019-11-21
帖子: 3,006
声望力: 66
poster 正向着好的方向发展
帖子 强制用户在Matlab中输入整数的最佳方法

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

我目前正在使用此:

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

编辑2:

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)) 编辑

这些将测试任何整数值。要将有效值限制为正整数,请添加一个num_dice > 0如@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

更多&回答...
poster 当前离线   回复时引用此帖
回复


发帖规则
不可以发表新主题
不可以发表回复
不可以上传附件
不可以编辑自己的帖子

启用 BB 代码
论坛禁用 表情符号
论坛启用 [IMG] 代码
论坛启用 HTML 代码



所有时间均为北京时间。现在的时间是 22:51


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