Vector isn't storing the values passed to it?

4 ビュー (過去 30 日間)
Ame Michael
Ame Michael 2018 年 5 月 11 日
編集済み: Stephen23 2018 年 5 月 11 日
I am going to ask a user to give me positive numbers, and I will quit once the user enters a negative number. Then, I will display all the positive numbers that they had entered. The code reads find to me, but for some reason, the array is not putting in the first positive number that the user passes to it... Any ideas will be greatly appreciated. Thank you.
i=0;
answer='Enter a positive number: ';
x=input(answer);
while x>0
x=input(answer);
i=i+1;
A(i)=x;
end

採用された回答

Stephen23
Stephen23 2018 年 5 月 11 日
pmt = 'Enter a positive number: ';
num = str2double(input(pmt,'s'));
vec = [];
while num>0
vec = [vec,num];
num = str2double(input(pmt,'s'));
end
And tested:
Enter a positive number: 5
Enter a positive number: 3
Enter a positive number: 1
Enter a positive number: -1
>> vec
vec =
5 3 1
Note that I used the 's' option and wrapped input in str2double, which avoids the unnecessary risk of the user inputting arbitrary code (which would then be executed by input) or unsuitable values.
  2 件のコメント
Ame Michael
Ame Michael 2018 年 5 月 11 日
Hello Stephen,
thank you so much for your help. Can you please tell me, what does the 's' option do? I removed it so see it's role in the script, leading to the script not running. Just curious, correct me if I am wrong, do I always use the 's' in conjunction with the str2double function?
Thank you very much.
Stephen23
Stephen23 2018 年 5 月 11 日
編集済み: Stephen23 2018 年 5 月 11 日
@Ame Michael: the 's' option is explained in the input help, which I am sure that you have read, so you will know that it makes input return the exact char vector that the user has entered, otherwise the input will be evaluated and the first output returned: experienced MATLAB users consider evaluating any arbitrary input to be insecure and a bad practice. At the very least it can lead to unpredictable errors unless you add a lot of checks on what was returned by input (e.g. array class and size). It is a lot simpler to use the 's' option and str2double, which always returns a scalar numeric (which is NaN if the input was not a valid number).

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by