How do I change the display of my answers if condition is not met?

12 views (last 30 days)
Aaron
Aaron on 28 Jun 2012
Here is what I have so far:
*format compact
a=input('Enter value for side a: ');
if a <= 0
disp('Not a valid input.');break;
end
b=input('Enter value for side b: ');
if b <= 0
disp('Not a valid input.');break;
end
c=input('Enter value for side c: ');
if c <= 0
disp('Not a valid input.');break;
if a > b+c
fprintf('\n');
disp('Error: Side "a" must be less than the sum of sides b & c.') %
elseif b > a+c
fprintf('\n');
disp('Error: Side "b" must be less than the sum of sides a & c.')
elseif c > a+b
fprintf('\n');
disp('Error: Side "c" must be less than the sum of sides a & b.')
end
fprintf('\n');
A=acosd((b^2+c^2-a^2)/(2*b*c));
B=acosd((a^2+c^2-b^2)/(2*a*c));
C=acosd((a^2+b^2-c^2)/(2*a*b));
disp('Results:')
fprintf('Angle A = %G',A);disp(' degrees')
fprintf('Angle B = %G',B);disp(' degrees')
fprintf('Angle C = %G',C);disp(' degrees') *
When the conditions that provide the "Error" message are not met, I still get something like:
Angle A = 180 degrees Angle B = 0 degrees Angle C = 0 degrees
But I would like to have my program display something when there could be no viable answers, like:
Angle A = NaN degrees Angle B = NaN degrees Angle C = NaN degrees
or
Any message I choose.

Accepted Answer

Sean de Wolski
Sean de Wolski on 28 Jun 2012
Why don't you use error() instead of disp('...') to actually abort the program when the error is encountered.
Or, to keep what you have and make the if-decision tree work:
if
elseif
elseif
else
%we haven't errored, woohoo!
fprintf('\n');
A=acosd((b^2+c^2-a^2)/(2*b*c));
B=acosd((a^2+c^2-b^2)/(2*a*c));
C=acosd((a^2+b^2-c^2)/(2*a*b));
disp('Results:')
fprintf('Angle A = %G',A);disp(' degrees')
fprintf('Angle B = %G',B);disp(' degrees')
fprintf('Angle C = %G',C);disp(' degrees') *
end

More Answers (0)

Community Treasure Hunt

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

Start Hunting!