您的位置:首页 > 编程语言 > C语言/C++

C语言求解一元二次方程

2019-03-17 16:38 106 查看
版权声明:转载请注明来源 https://blog.csdn.net/weixin_38679924/article/details/88621589

注意:
注意deta的判定条件。

/*-----------------------
功能:求解一元二次方程
无解时输出NAN
输入示例:
3
1 2.1 1
1 -2 1
1.3 1 1.2
输出示例:
-0.73 -1.37
1.00 1.00
NAN
-------------------------
Author: Zhang Kaizhou
Date: 2019-3-17 16:39:46
------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

typedef struct node{
float a, b, c;
struct node * pnext;
} Node;

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

int main(){
Node * phead = NULL, * ptail = NULL;
int n, i;
scanf("%d", &n);
for(i = 0; i < n; i++){
Node * pnew = (Node *)calloc(1, sizeof(Node));
scanf("%f %f %f", &pnew->a, &pnew->b, &pnew->c);
list_tail_insert(&phead, &ptail, pnew);
}
compute_res(phead);

return 0;
}

void compute_res(Node * phead){
float deta, res1, res2;
while(phead != NULL){
deta = phead->b * phead->b - 4 * phead->a * phead->c;
if(deta < 0){
printf("NAN\n");
}
if(deta == 0){
res1 = -phead->b / (2 * phead->a);
res2 = -phead->b / (2 * phead->a);
printf("%.2f %.2f\n", res1, res2);
}
if(deta > 0){
res1 = (-phead->b + sqrt(deta)) / (2 * phead->a);
res2 = (-phead->b - sqrt(deta)) / (2 * phead->a);
printf("%.2f %.2f\n", res1, res2);
}
phead = phead->pnext;
}
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: