Some issues with a basic while loop problem, help appreciated
22 views (last 30 days)
Show older comments
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
0 Comments
Accepted Answer
Matt Fig
on 21 Nov 2012
Edited: Matt Fig
on 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')
More Answers (0)
See Also
Categories
Find more on Loops and Conditional Statements in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!