MATLAB POWER函数正确使用及三角形判断程序报错求助
问题
为课程编写MATLAB小程序,用于判断三角形的边长及角度相关基础信息,编写的代码如下:
clc a= input('enter the length of the side a '); b=input('enter the length of the side b '); c=input('enter the length of the side c '); k="This triangle is "; if (a+b>=c || b+c>=a || a+c>=b) if (a==b && b==c) a='equilateral '; elseif (a==b && a~=c|| a==c && a~=b || b==c && b~=a) a='isosceles '; else a=' scalene'; end if ((a^2)+(b^2)==c^2 || (a^2)+(c^2)==b^2 || (b^2)+(c^2)==a^2) b='right.'; elseif (a^2+b^2>c^2 || a^2+c^2>b^2 || b^2+c^2>a^2) b='acute.'; else b='obtuse.'; end d=k+a+b; disp(d) else disp('sorry, you cant build triangle with those') end
运行时第21行报错:
Error using ^
矩阵求幂维度不正确,请检查矩阵是否为方阵且幂为标量。如需对矩阵每个元素单独运算,请使用逐元素幂运算POWER(.^)。
尝试将^替换为.^并添加括号后问题仍未解决,寻求帮助。
解决方案
核心问题
代码存在变量名冲突:最初用a、b存储边长数值,但后续将它们重新赋值为字符串(如a='equilateral '),导致后续计算平方时,实际是对字符串进行幂运算,这在MATLAB中不允许,因此报错。
修复步骤
- 重命名分类变量:将存储三角形类型和角度类型的变量改为与边长变量不冲突的名称,比如
side_type和angle_type。 - 修正三角形合法性判断逻辑:原代码用
||(逻辑或),但三角形的成立条件是任意两边之和严格大于第三边,需改为&&(逻辑与),同时将>=改为>(避免退化三角形的情况)。 - 统一使用逐元素幂运算:将所有
^替换为.^,确保数值运算的正确性(单个数值时两者效果一致,但养成逐元素运算的习惯更规范)。 - 修正锐角三角形判断逻辑:原代码用
||判断任意一组两边平方和大于第三边平方是错误的,锐角三角形要求所有角都是锐角,即三组两边平方和都要大于对应第三边的平方,需改为&&。
修复后完整代码
clc a = input('enter the length of the side a '); b = input('enter the length of the side b '); c = input('enter the length of the side c '); k = "This triangle is "; % 修正三角形合法性判断:必须同时满足任意两边之和大于第三边 if (a + b > c) && (b + c > a) && (a + c > b) % 判断边的类型,使用新变量side_type,避免覆盖a if (a == b) && (b == c) side_type = 'equilateral '; elseif (a == b && a ~= c) || (a == c && a ~= b) || (b == c && b ~= a) side_type = 'isosceles '; else side_type = 'scalene '; end % 判断角度类型,使用新变量angle_type,避免覆盖b if (a.^2 + b.^2 == c.^2) || (a.^2 + c.^2 == b.^2) || (b.^2 + c.^2 == a.^2) angle_type = 'right.'; elseif (a.^2 + b.^2 > c.^2) && (a.^2 + c.^2 > b.^2) && (b.^2 + c.^2 > a.^2) angle_type = 'acute.'; else angle_type = 'obtuse.'; end d = k + side_type + angle_type; disp(d) else disp('sorry, you cant build triangle with those') end
内容的提问来源于stack exchange,提问作者szybkiwinek
相关产品推荐
相关产品推荐

