Labfans是一个针对大学生、工程师和科研工作者的技术社区。 | 论坛首页 | 联系我们(Contact Us) |
![]() |
![]() |
#1 |
高级会员
注册日期: 2019-11-21
帖子: 3,006
声望力: 66 ![]() |
![]()
我正在用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 更多&回答... |
![]() |
![]() |