How to display warning message withing while loop?
조회 수: 1 (최근 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
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
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
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
댓글 수: 0
참고 항목
카테고리
Help Center 및 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!