ybt1034 计算三角形面积
时空限制 1000ms/64MB
题目描述
平面上有一个三角形,它的三个顶点坐标分别为(x1,y1), (x2,y2), (x3,y3),那么请问这个三角形的面积是多少,精确到小数点后两位。
输入
输入仅一行,包括6个单精度浮点数,分别对应x1, y1, x2, y2, x3, y3。
输出
输出也是一行,输出三角形的面积,精确到小数点后两位。
样例输入
0 0 4 0 0 3
样例输出
6.00
代码
法一:常规版本
#include<iostream>
#include<cmath>
#include<cstdio>
using namespace std;
int main(){
double x1,y1,x2,y2,x3,y3;
cin>>x1>>y1>>x2>>y2>>x3>>y3;
double a,b,c,p,s;
a = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
b = sqrt((x2-x3)*(x2-x3)+(y2-y3)*(y2-y3));
c = sqrt((x3-x1)*(x3-x1)+(y3-y1)*(y3-y1));
p = (a+b+c)/2;
s = sqrt(p*(p-a)*(p-b)*(p-c));
printf("%.2lf\n",s);
return 0;
}
法二:函数版本
#include<iostream>
#include<cmath>
#include<cstdio>
using namespace std;
double f(double x1,double y1,double x2,double y2){
return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}
double area(double a,double b,double c){
double p=(a+b+c)/2;
return sqrt(p*(p-a)*(p-b)*(p-c));
}
int main(){
double x1,y1,x2,y2,x3,y3;
cin>>x1>>y1>>x2>>y2>>x3>>y3;
double a,b,c;
a = f(x1,y1,x2,y2);
b = f(x2,y2,x3,y3);
c = f(x3,y3,x1,y1);
printf("%.2lf\n",area(a,b,c));
return 0;
}