How to display warning message withing while loop?

9 vues (au cours des 30 derniers jours)
Laura
Laura le 20 Oct 2013
Commenté : Image Analyst le 20 Oct 2013
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 commentaire
dpb
dpb le 20 Oct 2013
Ok, a hint... :)
BTW, congratulations on posting work so far and actually trying something...try
lookfor warning
and see what that gives ideas for.

Connectez-vous pour commenter.

Réponse acceptée

Evan
Evan le 20 Oct 2013
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 commentaire
Image Analyst
Image Analyst le 20 Oct 2013
Don't forget to wrap it in a uiwait()!

Connectez-vous pour commenter.

Plus de réponses (1)

Image Analyst
Image Analyst le 20 Oct 2013
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

Catégories

En savoir plus sur Loops and Conditional Statements dans Help Center et File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by