What is wrong with my Triangle Area Function Code

15 ビュー (過去 30 日間)
Ronan Downes
Ronan Downes 2016 年 10 月 3 日
回答済み: Ronan Downes 2016 年 10 月 3 日
HI Folks,
I am just getting started so lease take it easy on me.
I am trying to write a function that will take in 1 ,2 or 3 arguments. I am naming it triangle_area and as you can guess for one input an equilateral triangle is assumed, for 2 a right angled triangle and if three inputs are given they are checked at either end to make sure the triangle inequality is met. If not an appropriate error should be generated and if all is well it goes on to find the area of the general triangle.
function [A] = trianglearea(a,b,c)
if nargin ==1
A=a^2/sqrt(3)
elseif nargin==2
A =a*b/2
if c<=a-b
error( 'Silly you, c is too small.')
end
if c>=a+b
error( 'Silly you, c is too big.')
end
else s = (a+b+c)/2;
A = sqrt(s*(s-a)*(s-b)*(s-c));
end
  3 件のコメント
Adam
Adam 2016 年 10 月 3 日
c doesn't exist when nargin == 2 so why are you doing checks on it there?
Ronan Downes
Ronan Downes 2016 年 10 月 3 日
Thanks
I am getting closer
function [A] = triangle_area(a,b,c) if nargin ==1 A=a^2/sqrt(3)
elseif nargin==2 A =a*b/2 else
% b+c>a % error( 'Silly you, that triangle is impossible')
s = (a+b+c)/2;
A = sqrt(s*(s-a)*(s-b)*(s-c))
end
Just need to set up an alarm if too many arguments entered or if triangle inequality is broken
a>b+c b>a+c or c>a+b should all trigger alarms

サインインしてコメントする。

回答 (1 件)

Ronan Downes
Ronan Downes 2016 年 10 月 3 日
function [A] = triangle_area(a,b,c) if nargin ==1 A=a^2/sqrt(3) elseif nargin==2 A =a*b/2 else % b+c>a % error( 'Silly you, that triangle is impossible') s = (a+b+c)/2; A = sqrt(s*(s-a)*(s-b)*(s-c)) end

カテゴリ

Help Center および File ExchangeOperators and Elementary Operations についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by