Some issues with a basic while loop problem, help appreciated

21 ビュー (過去 30 日間)
Vidar
Vidar 2012 年 11 月 21 日
This code is supposed to ask the user for several values, and stop once the product of these values has exceeded 500. It should not accept negative values. It should then display the product, the number of values entered, and a list of those values.
One thing it does not do is display the list of values. The way it is set up now, it will only show the last value. How can I fix this?
Secondly, how do I make matlab ignore a negative input, but continue the loop with the previously entered values?
SCRIPT BELOW
product=1;
n=0;
while product <= 500
num=input('Enter a positive number ');
if num < 0
fprintf('This number is negative, enter another number \n');
end
n=n+1;
product=product*num;
end
fprintf('Product = %d \n',product)
fprintf('Numbers entered = %d \n',n)
fprintf('List of numbers = %d \n', num);
Thank you for your help

採用された回答

Matt Fig
Matt Fig 2012 年 11 月 21 日
編集済み: Matt Fig 2012 年 11 月 21 日
Try this out.
product=1;
n=0;
while product <= 500
num(n+1)=input('Enter a positive number ');
if num(n+1) < 0
fprintf('This number is negative, enter another number \n');
else
product = product*num(n+1);
n = n+1;
end
end
home
fprintf('\n\tProduct = %d \n',product)
fprintf('\tNumbers entered = %d\n\tList of numbers = ',n)
fprintf('%d,',num)
fprintf('\b\n\n')
  1 件のコメント
Vidar
Vidar 2012 年 11 月 21 日
This did the trick, thank you very much!

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

その他の回答 (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