How to display warning message withing while loop?

1 回表示 (過去 30 日間)
Laura
Laura 2013 年 10 月 20 日
コメント済み: Image Analyst 2013 年 10 月 20 日
I have been trying to write the following program:
"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. "
I have been having stuck at the same bit: 'the program should check if a negative number is entered, give a warning and then ask for another number'. I have been able to use the continue statement to make sure the program doesn't take any negative numbers into account but I don't know how to display a warning message when this happens.
This is what I have so far:
num=input('Enter a positive real number: ');
product=num;
sum=1;
while product<500
num=input('Enter a positive real number: ');
if num<=0
continue
end
product=num*product;
sum=sum+1;
end
Any hints or tips would be so helpful!
  1 件のコメント
dpb
dpb 2013 年 10 月 20 日
Ok, a hint... :)
BTW, congratulations on posting work so far and actually trying something...try
lookfor warning
and see what that gives ideas for.

サインインしてコメントする。

採用された回答

Evan
Evan 2013 年 10 月 20 日
How exactly do you want to display the warning message? Do you want a dialog box to appear? Do you just want a message to appear in the command prompt? Do you want it to be in the same format as and function like built-in MATLAB warnings? This will determine which function you want to choose. Here are some options:
help fprintf
help warning
help warndlg
Depending on which you choose, you would just insert in your conditional statement above the contine line.
  1 件のコメント
Image Analyst
Image Analyst 2013 年 10 月 20 日
Don't forget to wrap it in a uiwait()!

サインインしてコメントする。

その他の回答 (1 件)

Image Analyst
Image Analyst 2013 年 10 月 20 日
Try this:
if num <= 0
message = sprintf('I said it must be positive,\nnot negative like the %d you entered!', num);
uiwait(msgbox(message));
continue;
end

カテゴリ

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