How to enter negative values ​​and values ​​greater than 9 in input with string.

5 ビュー (過去 30 日間)
Luccas S.
Luccas S. 2021 年 4 月 14 日
コメント済み: Luccas S. 2021 年 4 月 14 日
clear
clc
n=10;
ii=1;
V=0;
display('number between 10 and 20!')
while ii<10
teste = input('Enter a value: ','s')
if strcmp(teste,'End')
display('You cannot type end before you have 10 values entered')
continue;
end
X(ii) = teste
V(ii) = str2num(X(ii))
ii = ii+1;
end
while (ii>10) | (ii<20)
teste = input('Enter a value: ','s')
if strcmp(teste,'End')
display('End Program')
break;
end
X(ii) = teste
V(ii) = str2num(X(ii))
ii = ii+1;
end

採用された回答

Khalid Mahmood
Khalid Mahmood 2021 年 4 月 14 日
%for 10 values, while ii<11 is needed whe we start with ii=1, and
%string(teste) to convert character array into string
clear,clc
n=10;
ii=1;
V=0;
display('number between 10 and 20!')
while ii<11
teste = input('Enter a value: ','s')
if strcmpi(teste,'End')
display('You cannot type end before you have 10 values entered')
continue;
end
X(ii) = string(teste)
V(ii) = str2num(X(ii))
ii = ii+1;
end
fprintf('\n loop 2:');
while (ii>10) | (ii<20)
teste = input('Enter a value: ','s')
if strcmpi(teste,'End')
display('End Program')
break;
end
X(ii) = teste
V(ii) = str2num(X(ii))
ii = ii+1;
end
  3 件のコメント
Adam Danz
Adam Danz 2021 年 4 月 14 日
It's also better to use str2double than str2um. See discussion.
Luccas S.
Luccas S. 2021 年 4 月 14 日
Okay, now it worked. I just had to reverse the order of the vectors X (ii) and V (ii).
X (ii) = str2double (test)
V (ii) = X (ii)
I didn't remember the strcmpi function, thanks.

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

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeExtend Testing Frameworks についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by