How to display user inputs
显示 更早的评论
hi iv got a problem with a homework question the question is:
Write a script that asks the user to enter positive real numbers until their product becomes is
greater than 500. The program should check if a negative number is entered, give a warning
and then ask for another number. When a value of 500 is exceeded, the program should
display the product of the numbers, state how many numbers were entered, and list the
numbers. Use fprintf commands to display results and make the output look tidy.
Here's what iv got so far.
r=500;
cnt=0;
n=input('Enter a positive integer: ');
while n<r,
if n<0
disp('Invalid number')
n=input('Enter a positive integer: ');
elseif n>0
n=n*n;
cnt=cnt+1;
disp(n);
end
end
fprintf('product=%i\n',n)
fprintf('numbers entered=%i\n',cnt)
The problem i have is getting the user to input a different number after the first number is entered and then displaying all the entered numbers.
Any hints or advice would be appreciated cheers.
回答(1 个)
Walter Roberson
2013-11-14
Your line
n=n*n
is wrong. That is for squaring the input, not for multiplying the existing total by the new input.
Hint:
n(cnt+1) = input('Enter a positive integer: ');
类别
在 帮助中心 和 File Exchange 中查找有关 Loops and Conditional Statements 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!