Matlab largest inputted number

2 views (last 30 days)
William Diuguid
William Diuguid on 24 Sep 2015
Edited: Walter Roberson on 24 Sep 2015
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 negative number, 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
  1 Comment
Walter Roberson
Walter Roberson on 24 Sep 2015
Edited: Walter Roberson on 24 Sep 2015
Is the user to enter one number at a time or any number on one line? If the user is to enter one number at a time then you should be doing the max() calculation after the loop.
The maximum to be calculated is not how many entries the user gave, not the count of them; it needs to be of the value they entered.
Also you need to terminate on any negative number, not just -1
Hint: if you already know the maximum the user has entered so far, then when you are given another input, you can immediately figure out the maximum of all the values including that input. You do not need to store the values.

Sign in to comment.

Answers (0)

Categories

Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!