Chinaunix首页 | 论坛 | 博客
  • 博客访问: 38513
  • 博文数量: 64
  • 博客积分: 2640
  • 博客等级: 少校
  • 技术积分: 670
  • 用 户 组: 普通用户
  • 注册时间: 2010-01-26 13:15
文章分类
文章存档

2010年(64)

我的朋友
最近访客

分类: C/C++

2010-01-26 13:53:35

2009-02-05 14:56


求三角形面积(海伦公式):
#include<iostream>
#include<cmath>
using namespace std;
struct point{
       double x,y;
};
double sqr(double x){
       return x*x;
}
      
double S_tri(point a,point b,point c);
int main(void){
    point a,b,c;
   
    cout<<"Enter a,b,c:";
    cin>>a.x>>a.y>>b.x>>b.y>>c.x>>c.y;
   
    cout<<"S="<<S_tri(a,b,c)<<endl;
   
    system("pause");
    return 0;
}
double S_tri(point a,point b,point c){
       double ab,bc,ca,p;
      
       ab = sqrt( sqr(b.x-a.x) + sqr(b.y-a.y) );
       bc = sqrt( sqr(b.x-c.x) + sqr(b.y-c.y) );
       ca = sqrt( sqr(a.x-c.x) + sqr(c.y-a.y) );
       p = 0.5*(ab+bc+ca);
      
       return sqrt(p*(p-ab)*(p-ca)*(p-bc) );
}
三角形面积(叉积):
#include<iostream>
using namespace std;
struct point{
       double x,y;
};
double abs(double x){
       return x>=0.0?x:-x;
}
double S_tri(point a,point b,point c);
int main(void){
    point a,b,c;
   
    cout<<"Enter a,b,c:";
    cin>>a.x>>a.y>>b.x>>b.y>>c.x>>c.y;
   
    cout<<"S="<<S_tri(a,b,c)<<endl;
   
    system("pause");
    return 0;
}
double S_tri(point a,point b,point c){
       return 0.5*abs(a.x*b.y - b.x*a.y +
                      b.x*c.y - c.x*b.y +
                      c.x*a.y - a.x*c.y);
}
判断点是否在三角形内:
#include<iostream>
using namespace std;
struct point{
       double x,y;
};
point operator-(point p1,point p2){
      point r;
     
      r.x = p1.x - p2.x;
      r.y = p1.y - p2.y;
     
      return r;
}
double vp(point p1,point p2);
bool inside_tri(point p,point a,point b,point c);
int main(void){
    point a,b,c,p;
   
    cout<<"Input a,b,c:";
    cin>>a.x>>a.y>>b.x>>b.y>>c.x>>c.y;
    cout<<"Input p:";
    cin>>p.x>>p.y;
   
    if(inside_tri(p,a,b,c) ) cout<<"Inside!";
    else cout<<"Outside!";
   
    system("pause");
    return 0;
}
double vp(point p1,point p2){
       return p1.x*p2.y - p2.x*p1.y;
}
      
bool inside_tri(point p,point a,point b,point c){
     double d1,d2,d3;
    
     d1 = vp(a-p,b-p);
     d2 = vp(b-p,c-p);
     d3 = vp(c-p,a-p);
    
     if(d1*d2*d3!=0.0){
        if(d1*d2<0.0) return false;
        if(d2*d3<0.0) return false;
     }
    
     return true;
}


阅读(178) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~