Matlab largest inputted number

16 ビュー (過去 30 日間)
William Diuguid
William Diuguid 2015 年 9 月 24 日
編集済み: Walter Roberson 2015 年 9 月 24 日
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 件のコメント
Walter Roberson
Walter Roberson 2015 年 9 月 24 日
編集済み: Walter Roberson 2015 年 9 月 24 日
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.

サインインしてコメントする。

回答 (0 件)

カテゴリ

Help Center および File ExchangeEntering Commands についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by