Some issues with a basic while loop problem, help appreciated

20 Ansichten (letzte 30 Tage)
Vidar
Vidar am 21 Nov. 2012
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

Akzeptierte Antwort

Matt Fig
Matt Fig am 21 Nov. 2012
Bearbeitet: Matt Fig am 21 Nov. 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')

Weitere Antworten (0)

Kategorien

Mehr zu Loops and Conditional Statements finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by