How to display user inputs

16 ビュー (過去 30 日間)
robert graham
robert graham 2013 年 11 月 14 日
回答済み: Walter Roberson 2013 年 11 月 14 日
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
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: ');

カテゴリ

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