简体   繁体   中英

Matlab - user input into array

I need to write a program that returns the largest number entered by a user. The user can enter as many numbers >= 0 as they want and when they enter a -1, the program will stop and return the largest number. I am really struggling to do this. So far, I have this:

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``
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)]);

You don't need to limit it to positive numbers but to answer your question, you can do this. And remove the || in < 0 || in < 0 to allow the user to choose negative numbers.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM