Some issues with a basic while loop problem, help appreciated

21 visualizaciones (últimos 30 días)
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

Respuesta aceptada

Matt Fig
Matt Fig el 21 de Nov. de 2012
Editada: Matt Fig el 21 de Nov. de 2012
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')

Más respuestas (0)

Categorías

Más información sobre Loops and Conditional Statements en Help Center y File Exchange.

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by