来源:大工慕课 链接
作者:Caleb Sung
从键盘输入三个数字代表三条线段的长度(表示线段长度的变量用双精度类型),如果三条线段能形成三角形则输出它是钝角、直角还是锐角三角形以及该三角形的面积(面积要求小数点后保留两位小数),如果不能形成三角形则输出“X.XX,X.XX,X.XX不能形成三角形。”(X.XX是输入的线段长度,要求小数点后保留两位小数。)
可先找到最大的边,然后根据它的平方与其他两边的平方和判断是什么类型的三角型。
scanf("%d%d", &a, &b) 用空格隔开
scanf("%d,%d", &a, &b) 用逗号隔开
下面这个代码是我一开始没看提示,直接算出三角形三个角度大小算出来的,和解答思路有一点区别,与之相匹配的代码在后面:
#include<stdio.h>
#include<math.h>void main()
{float side_1, side_2, side_3, angle_1, angle_2, angle_3, max=0.0, s=0.0;printf("Please enter the length of three side of a triangle: n");scanf("%f%f%f", &side_1, &side_2, &side_3);if((side_1 + side_2 > side_3) && (side_2 + side_3 > side_1) && (side_1 + side_3 > side_3)){angle_1 = 180.0 / M_PI * acos((side_2*side_2 + side_3*side_3 - side_1*side_1) / (2.0 * side_2 * side_3));angle_2 = 180.0 / M_PI * acos((side_1*side_1 + side_3*side_3 - side_2*side_2) / (2.0 * side_1 * side_3));angle_3 = 180.0 / M_PI * acos((side_1*side_1 + side_2*side_2 - side_3*side_3) / (2.0 * side_1 * side_2));s = 0.5 * side_1 * side_2 * sin(angle_3 * M_PI / 180.0);max = angle_1;if(angle_2 > max){max = angle_2;}if(angle_3 > max){max = angle_3;}if(max > 90.0){printf("This is an obtuse angled triangle.");}else if(max < 90.0){printf("This is an acute triangle.");}else{printf("This is a right angled triangle.");}printf("nThe area of the triangle is %.2lf", s);}else{printf("Sides with the length of %.2lf, %.2lf, %.2lf cannot not make up a triangle!", side_1, side_2, side_3);}}
下面这段代码是修改后的版本,运算效率较上一个有很大提高:
#include<stdio.h>
#include<math.h>int main(){double a, b, c, p, s, max, angle;printf("请输入三角形三边边长: n");scanf("%lf%lf%lf", &a, &b, &c);if (a+b>c && a+c>b && b+c>a){max = a;angle = acos((b*b+c*c-a*a)/(2*b*c))*180.0/M_PI;if(max < b){max = b;angle = acos((a*a+c*c-b*b)/(2*a*c))*180.0/M_PI;}if(max < c){max = c;angle = acos((a*a+b*b-c*c)/(2*a*b))*180.0/M_PI;}if(angle > 90.0){printf("这是个钝角三角形。");}else if(angle < 90.0){printf("这是个锐角三角形。");}else{printf("这是个直角三角形。");}p = 0.5 * (a + b + c);s = sqrt(p * (p - a) * (p - b) * (p - c));printf("这个三角形的面积为%.2lf。", s);}else{printf("%.2lf, %.2lf, %.2lf三边不能组成三角形。"); }
}
本文发布于:2024-02-04 08:25:40,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170703057753939.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |