Matlab - 用户输入到数组中

时间:2015-09-24 21:58:13

标签: arrays matlab

我需要编写一个返回用户输入的最大数字的程序。用户可以根据需要输入任意数量的> = 0,当他们输入-1时,程序将停止并返回最大数字。我真的很难做到这一点。到目前为止,我有这个:

validInput = false;
while (~validInput)
  fprintf('Enter a number >= 0 or a negative to quit.\n');
  num = input('Enter a number or -1 to quit: ');
  if(num == -1)
    validinput = true;
    counter = 0;
  elseif(num>=0)
    counter = counter+1;
  end;
  if(counter == 0)
    fprintf('No values entered!');
  else
    array = (counter);
     m = max(counter);
     disp(m);
  end
end``

2 个答案:

答案 0 :(得分:1)

enteredNumber = 0;
biggestNumber = 0;
while (enteredNumber ~= -1)
    enteredNumber = input('Enter a number : ');
    if enteredNumber > biggestNumber
        biggestNumber = enteredNumber;
    end
end
disp(['The biggest number entered is: ' num2str(biggestNumber)]);

答案 1 :(得分:1)

您不需要将其限制为正数,但要回答您的问题,您可以执行此操作。并删除|| in < 0以允许用户选择负数。

num = [];

while (true)
    in = input('Enter a number or a non-numeric character to quit: ');

    if isempty(in) || ~isnumeric(in) || in < 0
        break
    end

    num(end+1) = in;
end

[M, INDEX] = max(num);

if ~isempty(num)
    disp(['The ', num2str(INDEX),' was the maximum entered value and was: ', num2str(M), '.'])
else
    disp('No value entered.')
end