C语言海伦公式计算三角形面积

关键点:
1.注意scanf()函数的输入特点,回车符仍会留在输入缓冲区,故需注意及时清理输入缓冲区内容,避免造成输入逻辑的混乱;
2.注意三角形构成条件的判定。

/*--------------------------------------------------------------
功能:利用海伦公式求三角形面积,若三边无法构成三角形,则面积为0
输入示例:
3
1 2 3
3 4 5
5 12 13
输出示例:
0.00
6.00
30.00
Author: Zhang Kaizhou
Date: 2019-3-7 11:05:04
---------------------------------------------------------------*/
#include 
#include 
#include 

typedef struct node{
    float eadge[3];
    float area;
    struct node * pnext;
} Node;

void compute_area(Node * p);
void list_tail_insert(Node ** pphead, Node ** pptail, Node * p);
void list_print(Node * phead);

int main(){
    Node * phead = NULL, * ptail = NULL;
    int n, i;
    scanf("%d", &n);
    getchar(); // 取出输入缓冲区的回车符
    for(i = 0; i < n; i++){
        Node * pnew = (Node *)calloc(1, sizeof(Node));
        scanf("%f %f %f", &pnew->eadge[0], &pnew->eadge[1], &pnew->eadge[2]);
        compute_area(pnew);
        list_tail_insert(&phead, &ptail, pnew);
    }
    list_print(phead);

    free(phead);
    free(ptail);
    return 0;
}

void compute_area(Node * p){
    float a, b, c;
    float q; //半周长
    a = p->eadge[0];
    b = p->eadge[1];
    c = p->eadge[2];
    if(a + b < c || a + c < b || b + c < a || abs(a - b) > c || abs(a - c) > b || abs(b - c) > a){
        p->area = 0;
    }else{
        q = (a + b + c) / 2;
        p->area = sqrt(q * (q - a) * (q - b) * (q - c));
    }
    return;
}

void list_tail_insert(Node ** pphead, Node ** pptail, Node * p){
    if(* pphead == NULL){
        * pphead = p;
        * pptail = p;
    }else{
        (* pptail)->pnext = p;
        * pptail = p;
    }
    return;
}

void list_print(Node * phead){
    while(phead != NULL){
        printf("%.2f\n", phead->area);
        phead = phead->pnext;
    }
    return;
}

你可能感兴趣的:(C语言编程)