2

たとえば、私は


x = input('value = ?')

ユーザーが何も入力せずにEnterキーを押すだけで、このコマンドを繰り返すにはどうすればよいですか?

2つの入力変数を取得したように'


x = input('??');
y = input('???');
入力関数 y が表示されたときに x の最初の入力データを挿入した場合、最初の入力を編集できますか?

喜んで助けてくれる人に心から感謝します。

最初のケースの場合:

このようなコードが欲しいです


x = input('value = ?');
while x == %%no input%%
    x = input('value = ?'); %prompt the input command again
end


while x==error %% I want x in numeric input only
    x = input('value = ?'); %prompt the input command again
end

4

2 に答える 2

0

最初のケース:

x = input('??'); % if the user just hits 'enter' x is an empty variable
while isempty( x )
   x = input('??');
end

より堅牢な方法の場合

x = str2double( input('Your input here:', 's') );
while ~isnan( x )
    x = str2double( input('Your input here:', 's') );
end

コマンドinput('??', 's')は入力を「そのまま」返し、それを数値に変換しようとはしません。変換は、コマンドを介して行われstr2doubleます。ここで、入力が数値 (double) でないstr2double場合は、 を返しますNaN。これは でキャプチャできますisnan

これがうまくいくことを願っています。

于 2012-12-23T11:41:32.070 に答える
0

空白のために繰り返すために、

x=''
while isempty(x)
  x=input('value=');
end

非数値の場合、次のようなものを使用できます

x=''
while isempty(x)
  try
     x=input('value=')
  catch me
     fprintf('enter a number\n')
  end
end
于 2012-12-23T11:42:12.970 に答える