How to display warning message withing while loop?

8 次查看(过去 30 天)
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
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 CenterFile Exchange 中查找有关 Loops and Conditional Statements 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by