store user input in an array

16 ビュー (過去 30 日間)
Inifome Eleluwor
Inifome Eleluwor 2021 年 1 月 11 日
編集済み: KALYAN ACHARJYA 2021 年 1 月 11 日
Hello, I'm supposed to make a code that prompts the user to enter a positive real number to 1 decimal place. I should prompt the user 10 times. For instance the user enters 1 - 10. I am also supposed to store all the user inputs in an array. This was the code I used.
user_input_array = [];
for i = 1:10
user_input = fprintf('%.1f\n', input('Enter positive real number : '));
if user_input <= 0
break
else
user_input_array(end+1) = user_input;
end
end
user_input_array
the first code gives
4 4 4 4 4 4 4 4 4 5
The other code I used was
user_input_array = [];
for i = 1:10
user_input = input('Enter positive real number : ');
if user_input <= 0
break
else
user_input_array(end+1) = user_input;
end
end
user_input_array
The second code gives
1 2 3 4 5 6 7 8 9 10
The second code was good but the numbers were not to 1 decimal place
Does anyone know why the first code did not work?
  2 件のコメント
KSSV
KSSV 2021 年 1 月 11 日
What output you expect?
Inifome Eleluwor
Inifome Eleluwor 2021 年 1 月 11 日
1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10.0

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

回答 (2 件)

David Hill
David Hill 2021 年 1 月 11 日
user_input= zeros(1,10);
for i = 1:10
while user_input(i)<=0
user_input(i) = input('Enter positive real number : ');
end
end

KALYAN ACHARJYA
KALYAN ACHARJYA 2021 年 1 月 11 日
編集済み: KALYAN ACHARJYA 2021 年 1 月 11 日
user_input=zeros(1,10);
n=1;
while n<=10
user_input(n)=input('Enter positive real number : ');
n=n+1;
end
fprintf('user_input ');
fprintf(' %.1f',user_input)

カテゴリ

Help Center および File ExchangeNumeric Types についてさらに検索

タグ

Community Treasure Hunt

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

Start Hunting!

Translated by