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

2 visualizzazioni (ultimi 30 giorni)
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.

Risposta accettata

Sean de Wolski
Sean de Wolski il 28 Giu 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

Più risposte (0)

Categorie

Scopri di più su Creating and Concatenating Matrices in Help Center e File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by